There is a difference if the `ifelse` arguments can have side effects,
or if LLVM cannot determine whether they are always safe to execute.
Consider e.g.
```
x = if cond
    a[1]
else
    0
end
```
then LLVM won't know whether the array `a` is empty if `cond` is
false. If you know that `a` will not be empty, then you can write
instead
```
x = ifelse(cond, a[1], 0)
```
which might be faster since the load can be hoisted.

In general it's very difficult to know which is faster (`if` or
`ifelse`), and one usually has to experiment, look at the generated
disassembled code, and run benchmarks. I would not dare give a rule of
thumb here -- use whatever "looks better" in the source code.

-erik


On Wed, Mar 23, 2016 at 3:19 AM, Jeffrey Sarnoff
<[email protected]> wrote:
>   ifelse(condition::Bool, x, y)
>   Return x if condition is true, otherwise return y.
>   This differs from ? or if in that it is an ordinary function, so all the
> arguments are evaluated first.
>   In some cases, using ifelse instead of an if statement can eliminate the
> branch in generated code
>   and  provide higher performance in tight loops.
>
> What characterizes the cases where ifelse( condition, x, y ) eliminates the
> conditional branch?
>
>
>



-- 
Erik Schnetter <[email protected]>
http://www.perimeterinstitute.ca/personal/eschnetter/

Reply via email to