哪个具有更好的性能:test!= null或null!= test [英] Which has better performance: test != null or null != test

查看:58
本文介绍了哪个具有更好的性能:test!= null或null!= test的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两行代码

if (test ! = null)

if (null != test)

在性能上,以上两个语句是否有区别?我见过很多人使用后者,当被问及他们说这是最佳实践时,没有充分的理由.

Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.

推荐答案

没有区别.

第二个原因仅仅是因为C/C ++程序员总是进行赋值而不是进行比较.

Second one is merely because C/C++ where programmers always did assignment instead of comparing.

例如

// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}

虽然Java编译器会生成编译错误.

While java compiler will generate compilation error.

所以我个人更喜欢第一个,因为可读性强,人们倾向于从左到右阅读,如果test不等于null,则读为而不是null不等于test..

So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.

这篇关于哪个具有更好的性能:test!= null或null!= test的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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