Great question @tparker and great answer @ColinTBowers. Trying to think about both of them, it occurred to me to try the straightforward old school of the Julian Way-the-the-t20. The result was faster on the important input of a long vector of identical elements, so I am adding this note. Also, the name of the allequal function seems appropriate enough to mention. So here are the options:
allequal_1(x) = all(y->y==x[1],x) allequal_2(x) = foldl(==,x) # another way but doesn't short-circuit :( @inline function allequal_3(x) length(x) < 2 && return true e1 = x[1] i = 2 @inbounds for i=2:length(x) x[i] == e1 || return false end return true end
And the standard:
julia> using BenchmarkTools julia> v = fill(1,10_000_000);
UPDATE: Another important point for testing is when there is the possibility of a short circuit. Thus (on request in commment):
julia> v[100] = 2 2 julia> allequal_1(v),allequal_2(v),allequal_3(v) (false, false, false) julia> @btime allequal_1($v); 108.946 ns (1 allocation: 16 bytes) julia> @btime allequal_2($v); 10.325 ms (0 allocations: 0 bytes) julia> @btime allequal_3($v); 68.221 ns (0 allocations: 0 bytes)
The second version of allequal_2 does not work well, since it does not close.
All things being equal, the for version must be allequal in the database.
Dan getz
source share