java null 检查语法差异 [英] java null check syntactical difference

查看:43
本文介绍了java null 检查语法差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迄今为止发布的任何 Java 版本中是否存在性能差异

Has there ever been a performance difference in any of the java versions released to date between

foo != null

null != foo?

我个人不认为对象的上述两种空检查形式的行为有任何变化,但不确定哪一种表现更好.我知道差异会非常小(如果有的话),但想知道为什么有人以这种方式编写所有代码.

I personally do not think there is any change in behavior of the above two forms of null check of an object, but not sure about which one performs better. I know the difference will be very low, if any, but was wondering why someone had written all the code in that fashion.

推荐答案

这来自旧 C 时代.它以 foo == null (null == foo) 开头.

This came from old C times. And it started with foo == null (null == foo).

在 c 语法中是有效的(编译器没有抱怨):

In c syntax was valid (compiler did not complain):

if (foo = null) {
}

为了防止这种细微的错误,开始使用语法:

To prevent this subtle error syntax was started to use:

if (null == foo) {
}

因为 null 是常量 this如果(空 = foo){}

Because null is Constant this if (null = foo) { }

成为语法错误.

在java中只有一种情况很重要:

In java there is only one case where this matters:

boolean someBoolean;
if (someBoolean = true) {
}

是运行时错误,但可以编译

is runtime error, but compiles

这个

boolean someBoolean;
if (true = someBoolean) {
}

是编译错误.

没有性能问题,只是在某些情况下防止错误.

There is no performance issues, only error prevention in some cases.

这篇关于java null 检查语法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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