Yes, unfortunately, it's very hard to know which will be faster. If it was easy to tell, I suspect compilers would get this optimization right on their own more often. Even in simple, side-effect-free cases, I find that LLVM often won't do this transformation automatically. At the same time, sometimes it's a win, sometimes it's a loss and sometimes it's just a wash. Trying it out seems to be the best way to find out – and of course, it may vary across specific CPUs :-\
On Wed, Mar 23, 2016 at 8:44 AM, Erik Schnetter <[email protected]> wrote: > 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/ >
