哪个更有效:if(null == variable)或if(variable == null)? [英] Which is more effective: if (null == variable) or if (variable == null)?
问题描述
在Java中,哪个更有效,有什么区别?
In Java, which will be more effective, and what are the differences?
if (null == variable)
或
if (variable == null)
推荐答案
< sup>(与此问题类似: null == object and object =之间的差异= = null )
我想说这两个表达式之间的性能完全没有区别。
I would say that there is absolutely no difference in performance between those two expressions.
有趣的是,编译后的字节码(由Suns javac发出)在两种情况下看起来有点不同。
Interestingly enough however, the compiled bytecode (as emitted by Suns javac) looks a bit different for the two cases.
对于 boolean b = variable == null
:
3: aload_1 // load variable
4: ifnonnull 11 // check if it's null
7: iconst_1 // push 1
8: goto 12
11: iconst_0 // push 0
12: istore_2 // store
boolean b = null == variable
:
3: aconst_null // push null
4: aload_1 // load variable
5: if_acmpne 12 // check if equal
8: iconst_1 // push 1
9: goto 13
12: iconst_0 // push 0
13: istore_2 // store
正如@Bozho所说,变量== null
是最常见,默认和首选的样式。
As @Bozho says, variable == null
is the most common, default and preferred style.
但在某些情况下,我倾向于设置 null
在前面。例如,在以下情况中:
For certain situations however, I tend to put the null
in front. For instance in the following case:
String line;
while (null != (line = reader.readLine()))
process(line);
这篇关于哪个更有效:if(null == variable)或if(variable == null)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!