为什么要使用短路码?

发布于 2024-08-11 11:57:26 字数 1416 浏览 11 评论 0原文

相关问题使用短路评估的好处, 为什么语言不使用短路评估?< /a>, 有人可以解释一下这行吗请问代码? (逻辑和赋值运算符)

关于使用短路代码的语言的好处存在疑问,但我想知道对程序员有什么好处?难道只是为了让代码更简洁一点吗?还是有性能原因?

我并不是在询问需要评估两个实体的情况,例如:

if($user->auth() AND $model->valid()){
  $model->save();
}

对我来说,推理很清楚 - 因为两者都需要为真,所以如果用户无法保存模型验证,则可以跳过成本更高的模型验证数据。

(对我来说)这也有一个明显的目的:

if(is_string($userid) AND strlen($userid) > 10){
  //do something
};

因为使用非字符串值调用 strlen() 是不明智的。

我想知道的是当它不影响任何其他语句时使用短路代码。例如,从 Zend 应用程序默认索引页:

defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

这可能是:

if(!defined('APPLICATION_PATH')){
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
}

或者甚至作为单个语句:

if(!defined('APPLICATION_PATH'))
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

那么为什么要使用短路代码呢?只是为了使用逻辑运算符代替控制结构的“酷”因素?合并嵌套的 if 语句?因为更快?

Related Questions: Benefits of using short-circuit evaluation, Why would a language NOT use Short-circuit evaluation?, Can someone explain this line of code please? (Logic & Assignment operators)

There are questions about the benefits of a language using short-circuit code, but I'm wondering what are the benefits for a programmer? Is it just that it can make code a little more concise? Or are there performance reasons?

I'm not asking about situations where two entities need to be evaluated anyway, for example:

if($user->auth() AND $model->valid()){
  $model->save();
}

To me the reasoning there is clear - since both need to be true, you can skip the more costly model validation if the user can't save the data.

This also has a (to me) obvious purpose:

if(is_string($userid) AND strlen($userid) > 10){
  //do something
};

Because it wouldn't be wise to call strlen() with a non-string value.

What I'm wondering about is the use of short-circuit code when it doesn't effect any other statements. For example, from the Zend Application default index page:

defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

This could have been:

if(!defined('APPLICATION_PATH')){
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
}

Or even as a single statement:

if(!defined('APPLICATION_PATH'))
  define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

So why use the short-circuit code? Just for the 'coolness' factor of using logic operators in place of control structures? To consolidate nested if statements? Because it's faster?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

甜味拾荒者 2024-08-18 11:57:26

对于程序员来说,较不详细的语法相对于另一种更详细的语法的好处可以是:

  • 更少的键入,因此更高的编码效率,
  • 更少的阅读,因此更好的可维护性。

现在我只讨论不太冗长的语法在任何方面都不是棘手或聪明的,只是相同的公认的做法,但字符更少。

通常,当您在一种语言中看到特定的结构时,您希望您使用的语言也能具有这种结构,但之前甚至不一定意识到这一点。我脑海中浮现出一些例子:

  • Java 中的匿名内部类,而不是传递指向函数的指针(更多的代码行)。
  • 在 Ruby 中,||= 运算符用于计算表达式,如果计算结果为 false 或为 null,则为其赋值。当然,你可以通过 3 行代码实现同样的事情,但是为什么呢?
  • 还有更多...

For programmers, the benefit of a less verbose syntax over another more verbose syntax can be:

  • less to type, therefore higher coding efficiency
  • less to read, therefore better maintainability.

Now I'm only talking about when the less verbose syntax is not tricky or clever in any way, just the same recognized way of doing, but in fewer characters.

It's often when you see specific constructs in one language that you wish the language you use could have, but didn't even necessarily realize it before. Some examples off the top of my head:

  • anonymous inner classes in Java instead of passing a pointer to a function (way more lines of code).
  • in Ruby, the ||= operator, to evaluate an expression and assign to it if it evaluates to false or is null. Sure, you can achieve the same thing by 3 lines of code, but why?
  • and many more...
阳光下慵懒的猫 2024-08-18 11:57:26

用它来迷惑人!

Use it to confuse people!

手心的温暖 2024-08-18 11:57:26

我不懂 PHP,也从未见过在 C 系列语言的 if 或 while 条件之外使用短路,但在 Perl 中,这是非常惯用的说法:

open my $filehandle, '<', 'filename' or die "Couldn't open file: $!";

将所有内容都包含在一个语句中的一个优点是变量宣言。否则你不得不说:

my $filehandle;
unless (open $filehandle, '<', 'filename') {
    die "Couldn't open file: $!";
}

在这种情况下很难说第二个更干净。如果语言没有unless,它仍然会更加冗长

I don't know PHP and I've never seen short-circuiting used outside an if or while condition in the C family of languages, but in Perl it's very idiomatic to say:

open my $filehandle, '<', 'filename' or die "Couldn't open file: $!";

One advantage of having it all in one statement is the variable declaration. Otherwise you'd have to say:

my $filehandle;
unless (open $filehandle, '<', 'filename') {
    die "Couldn't open file: $!";
}

Hard to claim the second one is cleaner in that case. And it'd be wordier still in a language that doesn't have unless

戒ㄋ 2024-08-18 11:57:26

我认为你的例子是为了酷的因素。没有理由编写这样的代码。

编辑:出于惯用原因,我这样做没有问题。如果使用某种语言的其他人都使用短路求值来创建每个人都能理解的类似语句的实体,那么您也应该这样做。然而,我的经验是,此类代码很少用 C 系列语言编写。正确的形式只是像平常一样使用“if”语句,它将条件(可能没有副作用)与条件控制的函数调用(可能有很多副作用)分开。

I think your example is for the coolness factor. There's no reason to write code like that.

EDIT: I have no problem with doing it for idiomatic reasons. If everyone else who uses a language uses short-circuit evaluation to make statement-like entities that everyone understands, then you should too. However, my experience is that code of that sort is rarely written in C-family languages; proper form is just to use the "if" statement as normal, which separates the conditional (which presumably has no side effects) from the function call that the conditional controls (which presumably has many side effects).

情愿 2024-08-18 11:57:26

短路运算符在两种尚未提及的重要情况下非常有用:

情况 1。假设您有一个指针,可能是 NULL,也可能不是 NULL,并且您想检查它是否不是 NULL,并且它指向的东西不是 >0。但是,如果指针为 NULL,则不得取消引用该指针。如果没有短路运算符,您将不得不这样做:

if (a != NULL) {
  if (*a != 0) {
    ⋮
  }
}

但是,短路运算符允许您将其编写得更紧凑:

if (a != NULL && *a != 0) {
  ⋮
}

在某些知识中,*a不会如果 aNULL 则进行评估。

情况2。如果要将变量设置为从一系列函数之一返回的非 false 值,您可以简单地执行以下操作:

my $file = $user_filename ||
           find_file_in_user_path() ||
           find_file_in_system_path() ||
           $default_filename;

这将 $file 的值设置为 $user_filename 如果它存在,或者 find_file_in_user_path() 的结果,如果它是 true,或者...等等。这在 Perl 中可能比 C 中更常见,但我在 C 中见过它。

还有其他用途,包括您上面引用的相当人为的示例。但它们是一种有用的工具,也是我在使用不太复杂的语言进行编程时错过的工具。

Short circuit operators can be useful in two important circumstances which haven't yet been mentioned:

Case 1. Suppose you had a pointer which may or may not be NULL and you wanted to check that it wasn't NULL, and that the thing it pointed to wasn't 0. However, you must not dereference the pointer if it's NULL. Without short-circuit operators, you would have to do this:

if (a != NULL) {
  if (*a != 0) {
    ⋮
  }
}

However, short-circuit operators allow you to write this more compactly:

if (a != NULL && *a != 0) {
  ⋮
}

in the certain knowledge that *a will not be evaluated if a is NULL.

Case 2. If you want to set a variable to a non-false value returned from one of a series of functions, you can simply do:

my $file = $user_filename ||
           find_file_in_user_path() ||
           find_file_in_system_path() ||
           $default_filename;

This sets the value of $file to $user_filename if it's present, or the result of find_file_in_user_path(), if it's true, or … so on. This is seen perhaps more often in Perl than C, but I have seen it in C.

There are other uses, including the rather contrived examples which you cite above. But they are a useful tool, and one which I have missed when programming in less complex languages.

时间海 2024-08-18 11:57:26

与丹所说的相关,我认为这一切都取决于每种编程语言的约定。我看不出有什么区别,所以请按照每种编程语言的惯用方式进行操作。我想到的一件可能会产生影响的事情是,如果您必须进行一系列检查,在这种情况下,短路样式将比替代 if 样式更清晰。

Related to what Dan said, I'd think it all depends on the conventions of each programming language. I can't see any difference, so do whatever is idiomatic in each programming language. One thing that could make a difference that comes to mind is if you had to do a series of checks, in that case the short-circuiting style would be much clearer than the alternative if style.

晨与橙与城 2024-08-18 11:57:26

如果您有一个调用成本高昂(性能方面)的函数,该函数在右侧返回一个布尔值,您只想在另一个条件为真(或假)时调用该布尔值,该怎么办?在这种情况下,短路可以节省许多 CPU 周期。由于嵌套 if 语句较少,它确实使代码更加简洁。因此,出于您在问题末尾列出的所有原因。

What if you had a expensive to call (performance wise) function that returned a boolean on the right hand side that you only wanted called if another condition was true (or false)? In this case Short circuiting saves you many CPU cycles. It does make the code more concise because of fewer nested if statements. So, for all the reasons you listed at the end of your question.

孤芳又自赏 2024-08-18 11:57:26

事实就是性能。编译器中使用短路来消除死代码,从而节省文件大小和执行速度。在运行时,如果逻辑表达式中的其余子句的结果不影响答案,则短路不会执行它们,从而加快公式的计算速度。我很难记住一个例子。例如,

a AND b AND c

此公式中有两项从左到右计算。

如果 a AND b 的计算结果为 FALSE,则下一个表达式 AND c 可以是 FALSE AND TRUE 或 FALSE AND FALSE。无论 c 的值是多少,两者的计算结果都为 FALSE。因此,编译器不会在编译格式中包含 AND c,从而使代码短路。

为了回答这个问题,有一些特殊情况,编译器无法确定逻辑表达式是否具有常量输出,因此不会使代码短路。

The truth is actually performance. Short circuiting is used in compilers to eliminate dead code saving on file size and execution speed. At run-time short-circuiting does not execute the remaining clause in the logical expression if their outcome does not affect the answer, speeding up the evaluation of the formula. I am struggling to remember an example. e.g

a AND b AND c

There are two terms in this formula evaluated left to right.

if a AND b evaluates to FALSE then the next expression AND c can either be FALSE AND TRUE or FALSE AND FALSE. Both evaluate to FALSE no matter what the value of c is. Therefore the compiler does not include AND c in the compiled format hence short-circuiting the code.

To answer the question there are special cases when the compiler cannot determine whether the logical expression has a constant output and hence would not short-circuit the code.

橘寄 2024-08-18 11:57:26

可以这样想,如果您有一个类似“

if( A AND B )

机会是如果 A 返回 FALSE”的语句,那么您只会在极少数特殊情况下才需要评估 B。因此,不使用短路评估会令人困惑。

短路评估还可以防止另一个括号内的缩进和括号增加的趋势,从而使代码更具可读性。

Think of it this way, if you have a statement like

if( A AND B )

chances are if A returns FALSE you'll only ever want to evaluate B in rare special cases. For this reason NOT using short ciruit evaluation is confusing.

Short circuit evaluation also makes your code more readable by preventing another bracketed indentation and brackets have a tendency to add up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文