如果条件为真,则将表达式添加到循环中 [英] if condition is true, add an expression to a loop

查看:62
本文介绍了如果条件为真,则将表达式添加到循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找执行以下操作的最快,最优雅的方法:

I'm looking for the fastest and most elegant way to perform a following action:


const bool condition1;

(...)

if (condition1)
{
  // add an expression to a loop below
}

while (condition2)
{
  (...)
  // expression to be executed if condition1 = true
}

我当然可以在循环的每次迭代中检查条件,但是condition1是恒定的,因此它不是最有效的方法.

I could of course check the condition on every iteration of the loop, but condition1 is constant so it wouldn't be the most efficient way.

提前谢谢!

推荐答案

就像把分支放在循环中一样

Just put the branch in the loop like

while (condition2)
{
    if (condition1)
    {
      // run expression in the loop
    }
}

CPU具有分支预测变量,并且如果您的分支"变量存在,永远不会因为恒定的条件而分支,那么预测器将弄清楚这一点,并且您将永远不会真正地分支到代码执行中.

CPU's have a branch predictor and if your "branch" never branches because of a constant condition, then the predictor will figure that out and you'll never actually branch in your codes execution.

这篇关于如果条件为真,则将表达式添加到循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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