7cows
7cows

Reputation: 5034

Which is faster: my_bool=true; or if(!my_bool)?

The code below is expected to be executed many times

m_bool = true; //member variable

And m_bool will always remain true once the above code is executed.

If the following code was used instead, would it be more efficient, in terms of execution time?

if (!m_bool)
  m_bool = true;

Upvotes: 0

Views: 401

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

If the call is done multiple times, the if will become seamless because the branch predictor will become aware of the pattern.

The generated assembly becomes largely irrelevant, because the jmp will all but be skipped when reached.

If the compiler supports it, you can even use intrinsics (for example __builtin_expect) to provide that extra hint that the condition is most likely true.

Upvotes: 2

Related Questions