Fixing this does not entail so much overhead:
function range4(x)
isempty(x) && error("Does not support empty vectors")
min = typemax(eltype(x))
max = typemin(eltype(x))
hasnan = false
for xi in x
hasnan |= isnan(xi)
min = ifelse(min > xi, xi, min)
max = ifelse(max < xi, xi, max)
end
hasnan && error("Does not support NaNs in vectors")
return max - min
end
julia> x = 10 * rand(100);
julia> y = 10 * rand(1000000);
julia> @btime range4($x);
107.822 ns (0 allocations: 0 bytes)
julia> @btime extrema($x);
318.175 ns (0 allocations: 0 bytes)
julia> @btime range4($y);
1.397 ms (0 allocations: 0 bytes)
julia> @btime extrema($y);
3.285 ms (0 allocations: 0 bytes)
There is a ~3X gap here (persisting into large vectors), and this trivial (and popular) operation could probably be optimized further (SIMD, threads etc.)