What is faster in c++?
bool b1;
if(b1 == true)
orif(b1)
?if(b1 == false)
orif(!b1)
?
What is faster in c++?
bool b1;
if(b1 == true)
or if(b1)
?
if(b1 == false)
or if(!b1)
?
The C++11 language specification is a document (see its latest draft n3337) in English which don't talk about speed (at least of elementary statements).
You should not worry at all: any good C++ compiler would optimize (at least when asked, e.g. for GCC with g++ -O
or g++ -O2
etc...), probably giving the same machine code (or at least, code of similar performance).
BTW, how that is compiled and optimized heavily depends upon the target processor and the body of the if
(e.g. because of branch prediction). Sometimes, the compiler would figure out that using conditional moves could be faster than a conditional jump.
With GCC, there are very few cases where you might help the compiler using __builtin_expect
, but you should almost always not bother (and quite often bad or excessive use of that __builtin_expect
would slow down the computation). You might consider also using appropriately and with great care __builtin_prefetch
(see this) but again, you should usually not care.
Remember that premature optimization is evil (almost always).
Less interesting than the performance issue is simply that when you are dealing with classes (instead of Plain-Old-Data (POD) bool
) they don't mean the same thing. One might invoke an overloading of ==
while the other does a boolean conversion.
Consider this:
#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;
}
The output of that program will be:
Running overloading of ==
Running implicit cast to bool
(s1) branch ran.
It's a subtlety to be aware of. Although you cannot overload ==
for bool
itself, so your statements are equivalent--and will almost certainly perform the same.
Although the real answer is depends on the compiler, I would say that in 99% of the casas is the same. In both cases.