Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables 到';检查不等式并设置';或者只是';直接设置';变量_Variables - Fatal编程技术网

Variables 到';检查不等式并设置';或者只是';直接设置';变量

Variables 到';检查不等式并设置';或者只是';直接设置';变量,variables,Variables,哪一个更快: if (someValue != otherValue) someValue = otherValue; 或 还是将它们优化为相同的代码?在我使用的代码库中,大多数对象设置器都有如下功能: void SetSomeValue(T otherValue) { if(someValue!=otherValue) { cout << "Somevalue has changed from " << someValue <<

哪一个更快:

if (someValue != otherValue) someValue = otherValue;


还是将它们优化为相同的代码?

在我使用的代码库中,大多数对象设置器都有如下功能:

void SetSomeValue(T otherValue)
{
    if(someValue!=otherValue)
    {
       cout << "Somevalue has changed from " << someValue << " to " << othervalue << endl;
       someValue=otherValue;
    }
}
void SetSomeValue(T otherValue)
{
如果(someValue!=其他值)
{

cout这是一个微观优化的例子(参见主题)。如果你真的担心在项目中使用哪个,不要。很有可能这根本不重要

然而,如果你对理解为什么引擎盖下可能会有差异感兴趣,请继续阅读

是否存在速度差异(甚至哪一种可能在总体性能方面更好)取决于变量的数据类型、编程语言和用户的系统架构等因素

< C++ >使用int >代码> s,在大多数情况下,你的“直接设置”片段比你的“检查和设置”片段快。这是因为当值相等时执行的比较和分支(或比较和条件移动,或等价)实际上比(不需要的)慢。但是,差异太小了,在它产生差异之前,您必须多次这样做。此外,优化编译器可能会为您删除死代码

当然,也有可能的例外情况。一种可能的情况是缓存一致性多处理器系统,在这种情况下,即使值没有改变,写入也会导致其他处理器使其缓存线无效(我不确定这种情况发生的频率,但似乎至少是可能的)。然后,如果变量经常读取但很少更改(即代码运行多次,但通常是
someValue==otherValue
),则最好先执行检查。同样,在内存受限的程序中,如果缓存总是刷新到内存中(对于直写缓存),则执行检查可能是有意义的或者在写操作中设置脏位(对于回写缓存),即使该值没有更改(同样,听起来似乎合理)


如果
someValue
otherValue
是更复杂的类型,其中比较和/或赋值被覆盖,那么两段给定的代码甚至可能不相等,更不用说性能了。

只需使用更清楚地表达您意图的形式,不要担心(过早)优化。如有必要,您可以在以后分析和优化任何瓶颈。
void SetSomeValue(T otherValue)
{
    if(someValue!=otherValue)
    {
       cout << "Somevalue has changed from " << someValue << " to " << othervalue << endl;
       someValue=otherValue;
    }
}