哪个更有效:if (null == variable) 还是 if (variable == null)? [英] Which is more effective: if (null == variable) or if (variable == null)?

查看:36
本文介绍了哪个更有效:if (null == variable) 还是 if (variable == null)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,哪个更有效,有什么区别?

In Java, which will be more effective, and what are the differences?

if (null == variable)

if (variable == null)

推荐答案

(类似于这个问题:null==object 和 object==null 的区别)

我想说这两个表达式在性能上绝对没有区别.

I would say that there is absolutely no difference in performance between those two expressions.

然而,有趣的是,两种情况下编译的字节码(由 OpenJDKs javac 发出)看起来有点不同.

Interestingly enough however, the compiled bytecode (as emitted by OpenJDKs 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 所说,variable == 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆