Java如何处理单个IF语句中的多个条件 [英] How does Java deal with multiple conditions inside a single IF statement

查看:801
本文介绍了Java如何处理单个IF语句中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有这个:

if(bool1 && bool2 && bool3) {
...
}

现在。如果bool1被评估为false,Java是否足够智能,可以跳过检查bool2和bool2? java甚至从左到右检查它们?
我问这个是因为我正在排序我的if中的条件到它们所需要的时间(从左边最便宜的那个开始)。现在我不确定这是否给了我任何性能上的好处,因为我不知道Java如何处理这个问题。

Now. Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false? Does java even check them from left to right? I'm asking this because i was "sorting" the conditions inside my if's by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.

推荐答案

是的,Java(类似于其他主流语言)使用 懒惰评估 短路,这意味着它尽可能少地评估。

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

这意味着以下代码是完全安全的:

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

此外, a || b 永远不会评估 b 如果 a 评估为 true

Also, a || b never evaluates b if a evaluates to true.

这篇关于Java如何处理单个IF语句中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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