Set up test data
julia> bs = rand(Bool, 100000);
Using if/else:
julia> function foo(bs)
s = 0
for b in bs
if b
s += foo2()
else
s += foo3()
end
end
return s
end
foo (generic function with 1 method)
julia> foo2() = 1
foo2 (generic function with 1 method)
julia> foo3() = -1
foo3 (generic function with 1 method)
julia> @btime foo($bs)
27.500 μs (0 allocations: 0 bytes)
-280
Using dynamic dispatch
julia> function bar(bs)
s = 0
for b in bs
s += bar(b)
end
return s
end
bar (generic function with 4 methods)
julia> bar(b::Bool) = bar(Val(b))
bar (generic function with 4 methods)
julia> bar(::Val{true}) = 1
bar (generic function with 4 methods)
julia> bar(::Val{false}) = -1
bar (generic function with 4 methods)
julia> @btime bar($bs)
18.420 ms (0 allocations: 0 bytes)
-280