简体   繁体   English

带有布尔变量的运算符“==”的性能?

[英]Performance of operator '==' with boolean variable?

I guess this situation came across in every programmer,where we can use comparison operator '==',in my case situation is like this,a c++ pgm我想这种情况在每个程序员中都遇到过,我们可以使用比较运算符“==”,在我的情况下,情况是这样的,一个 c++ pgm

code 1:This has been used in all files except constructor代码 1:这已用于除构造函数之外的所有文件中

if(a==10)
{
 //do something;
}

but i can do the same as above with the following way, i set a bool variable to true when variable a becomes 10 in constructor itself,ie但是我可以通过以下方式执行与上述相同的操作,当变量a在构造函数本身中变为 10 时,我将 bool 变量设置为 true,即

constructor_name()
{
 boolean variable_name=TRUE;//when a == 10;
}

then i use the following code in my all files instead of code 1,然后我在我的所有文件中使用以下代码而不是代码 1,

code 3:代码3:

if(variable_name)
{
 //do same as first code
}

which is better for performance ,the code 1 or code 3.I hope i have illustrated my situation so than you can understand.Please help me.Thanks in advance.哪个对性能更好,代码 1 或代码 3。我希望我已经说明了我的情况,以便您能理解。请帮助我。提前致谢。

You shouldn't micro-optimize.你不应该微优化。 You will hardly notice any difference between your 2 version in performance (maybe you will save 1 CPU cycle), but it is not worth the time and effort, especially because nowadays CPUs are really fast.你几乎不会注意到你的 2 个版本在性能上有什么区别(也许你会节省 1 个 CPU 周期),但值得花时间和精力,特别是因为现在 CPU 真的很快。

Only optimize if you profile and find a bottleneck in your code.当您分析并发现代码中的瓶颈时才进行优化。

Look at it this way, if you store the boolean variable in the class, it uses memory (1 byte) for maybe saving 1 CPU cycle.这样看,如果将布尔变量存储在类中,它会使用内存(1 个字节)来节省 1 个 CPU 周期。 Depending on how often you create the class, that can scale up (even though the amount would still be ridiculously small).根据您创建类的频率,可以按比例增加(即使数量仍然小得离谱)。 You maybe saved 1 cycle, but you lost 1 byte.您可能节省了 1 个周期,但您丢失了 1 个字节。

If you wrote this in production code, I am sure that others would find it confusing (I would), and wonder why you put a isTen boolean in the class, instead of just comparing the value using operator== .如果您在生产代码中编写此代码,我相信其他人会发现它令人困惑(我会),并想知道为什么您在类中放置isTen布尔值,而不是仅使用operator==比较值。

Also, there may be a bug if you change a outisde of the constructor to 10 , then isTen would still be false , but a is 10 !此外,如果您将构造函数a外部更改为10 ,则可能存在false ,然后isTen仍然为false ,但a10

I found the below thing would make a difference,我发现下面的事情会有所作为,

consider variable a is an integer variable and it takes 4 bytes(assuming 4bytes for int),then compiler has to perform comparision of 4 bytes of memory where as a bool variable takes 1byte ,i guess this makes a differance in performance.考虑变量a是一个整数变量,它需要 4 个字节(假设 int 为 4 个字节),然后编译器必须执行 4 个字节的内存比较,而 bool 变量需要 1 个字节,我想这会影响性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM