短路与非短路操作员 [英] Short circuit vs non short circuit operators

查看:77
本文介绍了短路与非短路操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解以下区别(至少对于Java):

I understand the difference below (at least for Java):

if( true || false ) // short-circuiting boolean operator
if( true | false )  // non-short-circuiting boolean operator

但是我的问题是,在处理布尔表达式时,是否有任何理由使用非短路运算符?是否存在一些性能上的好处或使用上不会被认为是不好的?练习吗?

But my question is, is there any reason to use the non-short-circuiting operator when you are dealing with boolean expressions? Is there some performance benefit or use that wouldn't be considered bad practise?

推荐答案

您可能要使用非短路运算符的一个原因是,如果您某种程度上取决于函数的副作用.例如.

One reason you might want to use the non-short-circuiting operator is if you are somehow depending on side-effects of functions. For example.

boolean isBig(String text) {
  System.out.println(text);
  return text.length() > 10;
}

...
if( isBig(string1) || isBig(string2) ){
   ...
}

如果您不关心是否执行了 println ,则应使用上述短路操作.但是,如果要始终打印两个字符串(因此取决于副作用),则需要使用非短路运算符.

If you don't care about whether the println is executed then you should use the short circuit operations as above. However, if you want both strings to be printed always (thus depending on side effects) then you need to use the non-short-circuit operator.

实际上,您几乎总是想使用短路运算符.依靠表达式的副作用通常是不好的编程习惯.

Practically speaking, you almost always want to use the short-circuit operators. Relying on side effects in expressions is usually bad programming practice.

一个例外是在非常低级别或对性能敏感的代码中.短路运算符可能会稍慢一些,因为它们会导致程序执行中的分支.同样,使用按位运算符可以让您将32或64个并行布尔运算作为单个整数运算进行,这非常快.

One exception is in very low level or performance-sensitive code. The short-circuiting operators can be slightly slower because they cause branching in the program execution. Also using bitwise operators allows you to do 32 or 64 parallel boolean operations as a single integer operation, which is very fast.

这篇关于短路与非短路操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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