Suppose I have this code:
cond = true
a = cond ? 1 : 2
b = ifelse(cond, 1, 2)
What is the difference between the two operations?
Suppose I have this code:
cond = true
a = cond ? 1 : 2
b = ifelse(cond, 1, 2)
What is the difference between the two operations?
In the example you wrote, there is no effective difference. If, however, the two branches were more complicated than simple integer literals, then there is a difference:
julia> f() = (println("calling f()!"); 1)
f (generic function with 1 method)
julia> g() = (println("calling g()!"); 2)
g (generic function with 1 method)
julia> cond ? f() : g()
calling f()!
1
julia> ifelse(cond, f(), g())
calling f()!
calling g()!
1
In other words, ifelse
is just a normal function. And just like all other functions, its arguments are always evaluated. The ternary operator is syntax equivalent to:
if cond
f()
else
g()
end
Note that in some cases, this can result in a difference in the instructions your processor uses (that is, changing a branch to a lookup) which can have subtle performance implications beyond the costs of the code in the two branches (or not so subtle if inside a @simd
loop)... but often Julia and LLVM are often smart enough to do the best thing either way if it's possible.
Another general difference is that the ifelse
function can be broadcasted
julia> ifelse.([true, true, false], [1, 1, 1], [0, 0, 0])
3-element Vector{Int64}:
1
1
0
whereas the ternary operator cannot.
© 2022 - 2024 — McMap. All rights reserved.
if
statement on one line. I often prefer that look.if cond 1 else 2 end
. – Indra