Skip to content

Add allequal #43353

@CameronBieganek

Description

@CameronBieganek

Since we already have allunique, it might make sense to also add allequal. One reason to add allequal is that a proper implementation is much faster than the naive length(unique(itr)) == 1.

function allequal(x)
    first, rest = Iterators.peel(x)

    for v in rest
        if v == first
            continue
        else
            return false
        end
    end

    true
end

slow_allequal(x) = length(unique(x)) == 1
julia> using BenchmarkTools

julia> x = randn(1000); y = fill(1, 1000);

julia> @btime allequal($x);
  3.288 ns (0 allocations: 0 bytes)

julia> @btime slow_allequal($x);
  36.791 μs (27 allocations: 65.95 KiB)

julia> @btime allequal($y);
  475.082 ns (0 allocations: 0 bytes)

julia> @btime slow_allequal($y);
  3.816 μs (6 allocations: 608 bytes)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions