`ifelse` 和 Julia 中的三元运算符有什么区别? [英] What is the difference between `ifelse` and the ternary operator in Julia?
问题描述
假设我有这个代码:
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
换句话说,ifelse
只是一个普通的函数.就像所有其他函数一样,它的参数总是被评估.三元运算符的语法等价于:
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
请注意,在某些情况下,这可能会导致处理器使用的指令不同(即,将分支更改为查找),这可能会对两个分支中的代码成本(或如果在 @simd
循环中,则不是那么微妙)...但通常 Julia 和 LLVM 通常足够聪明,如果可能的话,无论哪种方式都可以做到最好.
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.
这篇关于`ifelse` 和 Julia 中的三元运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!