C ++ if语句速度

时间:2014-09-25 11:53:00

标签: c++ optimization

c ++的速度有多快?

bool b1;

  1. if(b1 == true)if(b1)

  2. if(b1 == false)if(!b1)

3 个答案:

答案 0 :(得分:3)

C++11语言规范是一份英文文档(请参阅最新草稿n3337),其中没有谈论速度(至少是基本语句)

你根本不用担心:任何优秀的C ++编译器都会optimize(至少在被问到时,例如GCCg++ -Og++ -O2等... ,可能提供相同的机器代码(或至少是类似性能的代码)。

BTW,编译和优化的方式在很大程度上取决于目标处理器和if的主体(例如因为branch prediction)。有时,编译器会发现使用条件移动可能比条件跳转更快。

使用GCC,极少数情况下你可以使用__builtin_expect来帮助编译器,但是你几乎总是不会打扰(而且往往是错误或过度使用this 1}}会减慢计算速度)。你也可以考虑适当而谨慎地使用__builtin_expect(见premature optimization is evil),但是你应该不在乎。

请记住{{3}}(几乎总是)。

答案 1 :(得分:3)

比性能问题更有趣的只是当你处理类(而不是普通旧数据(POD)bool时,它们并不意味着同样的事情。有人可能会调用==的重载,而另一个执行布尔转换。

考虑一下:

#include <iostream>
using namespace std;

class Something {
public:
    operator bool() const {
        cout << "Running implicit cast to bool\n";
        return true;
    }
};

bool operator==(Something const & left, bool const & right) 
{
    cout << "Running overloading of ==\n";
    return false;
}

int main() {
    Something s1;
    if (s1 == true) {
        cout << "(s1 == true) branch ran.\n";
    }
    if (s1) {
        cout << "(s1) branch ran.\n";
    }
    return 0;
}

该计划的输出将是:

Running overloading of ==
Running implicit cast to bool
(s1) branch ran.

要注意这一点是微妙的。虽然你不能为==本身重载bool,所以你的陈述是等价的 - 几乎可以肯定也是如此。

答案 2 :(得分:2)

虽然真正的答案是取决于编译器,但我会说99%的casas是相同的。在这两种情况下。