Julia's Short Circuit
Overview
In Julia, &&
and ||
not only perform logical AND and OR operations but also execute short-circuit evaluation1. For instance, A && B
returns true only if both A
and B
are true, but in reality, if A
is false, there is no need to check whether B
is true or false; A && B
is false. Short-circuit evaluation essentially skips checking B
. Skipping the calculation for B
can lead to performance improvements in some cases.
See Also
Speed Comparison
M = rand(0:2, 10^4, 10^4);
print(first(M))
@time if first(M) == 2 && sum(M) < 1000
print("!!")
end
@time if sum(M) < 1000 && first(M) == 2
print("!!")
end
The only difference between the two conditionals is the order of sum(M) < 1000
and first(M) == 2
, yet they perform exactly the same task. However, since first(M) == 2
merely checks if the first element of matrix M
is 2
, and sum(M)
sums up all elements, traversing through them, the latter relatively takes longer to compute.
julia> M = rand(0:2, 10^4, 10^4);
julia> print(first(M))
0
If the first element of M
is 0
as shown above, there is no need to calculate sum(M)
to see if sum(M) < 1000
. The speeds can vary significantly just by changing the order.
julia> @time if first(M) == 2 && sum(M) < 1000
print("!!")
end
0.000009 seconds
julia> @time if sum(M) < 1000 && first(M) == 2
print("!!")
end
0.040485 seconds (1 allocation: 16 bytes)
Environment
- OS: Windows
- julia: v1.7.0