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

2

5

Suppose I have this code:

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

What is the difference between the two operations?

Dosia answered 15/1, 2021 at 18:16 Comment(1)
Note that you can also write a normal if statement on one line. I often prefer that look. if cond 1 else 2 end.Indra
N
9

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.

Nuggar answered 15/1, 2021 at 18:43 Comment(0)
B
1

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.

Bambara answered 7/7, 2023 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.