C ++:仅在未设置时设置布尔值 [英] C++: Set bool value only if not set

查看:30
本文介绍了C ++:仅在未设置时设置布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 C++ 应用程序中有通常执行此操作的代码:

I have code in my C++ application that generally does this:

bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
    if (...) {
        // statements, unrelated to myFlag
    } else {
        // set myFlag to true, perhaps only if it was false before?
    }
}
if (myFlag) {
    // Do something...
}

我的问题与我的代码的 else 语句有关.基本上,我的循环可能会根据不满足的某个条件将 myFlag 的值从 false 设置为 true.永远不会将标志从真设置为假.我想知道哪种语句在性能方面更有意义,也许由于编译器优化,这个问题实际上不是问题.

The question I have pertains to the else statement of my code. Basically, my loop may set the value of myFlag from false to true, based on a certain condition not being met. Never will the flag be unset from true to false. I would like to know what statement makes more sense performance-wise and perhaps if this issue is actually a non-issue due to compiler optimization.

myFlag = true;

if (!myFlag) myFlag = true;

我通常会选择前者,因为它需要编写的代码更少.但是,我开始怀疑它是否涉及对内存的不必要写入,因此如果 myFlag 已经为真,后者将阻止不必要的写入.但是,使用后者是否会因为有条件语句而需要更多时间,因此需要使用更多指令来编译代码?

I would normally choose the former because it requires writing less code. However, I began to wonder that maybe it involved needless writing to memory and therefore the latter would prevent needless writing if myFlag was already true. But, would using the latter take more time because there is a conditional statement and therefore compile code using more instructions?

或者是我想太多了……

只是为了澄清一点......我后一种情况的目的是如果变量已经为真,则不写入内存.因此,仅当变量为 false 时才写入内存.

Just to clarify a bit...the purpose of my latter case is to not write to memory if the variable was already true. Thus, only write to memory if the variable is false.

推荐答案

几乎可以肯定,只使用 myFlag = true; 会更好.

You're almost certainly better off just using myFlag = true;.

if (!myFlag) myFlag = true; 的最大希望是编译器会注意到 if 无关紧要并对其进行优化.特别是,if 语句需要读取 myFlag 的当前值.如果该值尚未在缓存中,则意味着指令将在等待从内存中读取数据时停止.

About the best you can hope for from the if (!myFlag) myFlag = true; is that the compiler will notice that the if is irrelevant and optimize it away. In particular, the if statement needs to read the current value of myFlag. If the value isn't already in the cache, that means the instruction will stall while waiting for the data to be read from memory.

相比之下,如果你只是写(没有先测试)值可以被写入一个写队列,然后更多的指令可以立即执行.直到/除非您读取 myFlag 的值,否则您不会出现停顿(并且假设它在写入后很快就被读取,它可能仍然在缓存中,因此停顿将是最小的).

By contrast, if you just write (without testing first) the value can be written to a write queue, and then more instructions can execute immediately. You won't get a stall until/unless you read the value of myFlag (and assuming it's read reasonably soon after writing, it'll probably still be in the cache, so stalling will be minimal).

这篇关于C ++:仅在未设置时设置布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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