Alex Rivera | Logout

Does "if ([bool] == true)" require one more step than "if ([bool])"?

Asked 2009-07-01T16:20:10.590
31

This is a purely pedantic question, to sate my own curiosity.

I tend to go with the latter option in the question (so: if (boolCheck) { ... }), while a coworker always writes the former (if (boolCheck == true) { ... }). I always kind of teased him about it, and he always explained it as an old habit from when he was first starting programming.

But it just occurred to me today that actually writing out the whole == true part may in fact require an additional step for processing, since any expression with a == operator gets evaluated to a Boolean value. Is this true?

In other words, as I understand it, the option without the == true line could be loosely described as follows:

  1. Check X

While the option with the == true line would be more like:

  1. Let Y be true if X is true, otherwise false
  2. Check Y

Am I correct? Or perhaps any normal compiler/interpreter will do away with this difference? Or am I overlooking something, and there's really no difference at all?

Obviously, there will be no difference in terms of actual observed performance. Like I said, I'm just curious.

EDIT: Thanks to everyone who actually posted compiled results to illustrate whether the steps were different between the two approaches. (It seems, most of the time, they were, albeit only slightly.)

I just want to reiterate that I was not asking about what is the "right" approach. I understand that many people favor one over the other. I also understand that, logically, the two are identical. I was just curious if the actual operations being performed by the CPU are exactly the same for both methods; as it turns out, much of the time (obviously it depends on language, compiler, etc.), they are not.

Edit
Report

1 Answer

12

The compiler should generate the same code. However, comparing with true is arguably better because it is more explicit. Generally I don't do the explicit comparison, but you shouldn't make fun of him for doing it.

Edit: The easiest way to tell is to try. The MS compiler (cl.exe) generates the same number of steps in assembly:

int _tmain(int argc, _TCHAR* argv[])
{
    bool test_me = true;

    if (test_me) {
004113C2  movzx       eax,byte ptr [test_me] 
004113C6  test        eax,eax 
004113C8  je          wmain+41h (4113E1h) 
        printf("test_me was true!");
    }

    if (test_me == true) {
004113E1  movzx       eax,byte ptr [test_me] 
004113E5  cmp         eax,1 
004113E8  jne         wmain+61h (411401h) 
        printf("still true!");
    }
    return 0;
}

At this point the question is do test and cmp have the same cost? My guess is yes, though experts may be able to point out differences.

The practical upshot is you shouldn't worry about this. Chances are you have way bigger performance fish to fry.

answered 2009-07-01T16:23:01.010

Your Answer