哪些比较运算符的处理器效率更高:<、<=、!= 或 ==? [英] What comparison operators are more processor efficient: <, <=, != or ==?

查看:182
本文介绍了哪些比较运算符的处理器效率更高:<、<=、!= 或 ==?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以选择比较操作的类型,请按照处理器效率从高到低的顺序排列:

I have the choice between types of comparison operations, please put them in the order of efficiency for the processor starting with the most efficient:

if (x == 1)

if (x != 0)

if (x < 2)

if (x <= 3)

我经常面临这样的情况,我可以使用我选择的任何一种来获得相同的结果......

Often I am faced with case where I can use any of them I choose for the same outcome...

这是我一直想知道的,可能其他人也想知道.此外,它是否因不同的编程语言而异?

This is something I've always wanted to know and probably some other people want to know it too. Also, does it vary for different programming languages or not?

感谢您提供信息.因为它们显然都具有相同的效率,这意味着我可以使用 more > 或 <键入运算符以便更好地捕捉故障!

推荐答案

通常,它们中的任何一个都比其他的更有效率.这是因为在大多数 CPU 上,它们映射到专门的操作码,其执行由完全相同的物理单元处理,配置略有不同.使用不存在但很容易理解的汇编语法,每个分支(if 条件)可能会转换为:

Usually, any of them is more efficient than the others. This is because on most CPUs, they map to specialized opcodes, whose execution is handled by the very same physical unit, in slightly different configurations. Using a non-existent but very simple to understand assembly syntax, each branch (if condition) might translate to:

if (x == 1)
    test = x - 1
    branch_equal_zero test

if (x != 0)
    test = 0
    branch_non_equal_zero test

if (x < 2)
    test = x - 2
    branch_lower_than_zero test

if (x <= 3)
    test = x - 3
    branch_lower_or_equal_to_zero test

如您所见,与零相比(无论比较如何)可能更快,因为不涉及减法——但在如此微小的秒数中您可能 只有在非常重的负载下才会注意到它.

As you can see, comparing to zero (regardless of the comparision) might be faster because there is no subtraction involved -- but faster of such a tiny fraction of second you might notice it only under extremely heavy load.

即使我们说的是解释型语言(PHP 和 JS),答案也不会改变,因为所有运算符都由解释器直接映射到底层的本机比较.更不用说可能发生的任何类型转换或中间转换了.

Even if we are speaking of interpreted languages (PHP and JS), the answer does not change, because all operators are directly mapped to the underlying native comparisions by the interpreters. Let alone any type cast or intermediate conversion that might take place.

这篇关于哪些比较运算符的处理器效率更高:&lt;、&lt;=、!= 或 ==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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