What is the difference between `ifelse` and the ternary operator in Julia?

Viewed 271

Suppose I have this code:

cond = true
a = cond ? 1 : 2
b = ifelse(cond, 1, 2)

What is the difference between the two operations?

1 Answers

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.

Related