-2

I'd like to know if there is a big loss of performance if instead of using

if (MyBoolean) 

i use

if (MyBoolean == true)

I have always been told that == boolean was a stupid instructino because all the langages understand if(bool) but i wonder if there is a real difference between those two way of evaluating a boolean expression.

Thank you for reading

user2417992
  • 204
  • 1
  • 6
  • 16
  • Maybe you can look at this http://stackoverflow.com/questions/1070063/does-if-bool-true-require-one-more-step-than-if-bool – rjovic May 31 '13 at 09:52
  • 3
    This type of change would make such a small difference that it becomes completely irrelevant. The question you should be asking is which is more readable. – neelsg May 31 '13 at 09:53
  • 3
    **Never** use `if (MyBoolean == true)` in languages like C, where "true" is any non-zero value. – Paul R May 31 '13 at 09:55
  • 1
    Even if there were a difference *(there's not)*, it would be irrelevant - beginners always seem to overestimate the importance of small optimizations, not understanding just how fast computers are. If you could do in one second what a computer can do in one nanosecond *(which is approximately how long this statement would take)*, it would take you **31 years** to do what a computer can do in one second. Don't waste your time worrying about this until you better understand how computers work. – BlueRaja - Danny Pflughoeft May 31 '13 at 09:57

2 Answers2

1

No. Compilers are very smart. They will generate same binary code.

Ankush
  • 2,454
  • 2
  • 21
  • 27
  • 1
    Not necessarily, especially not in the many languages where both expressions are not equivalent. – harold May 31 '13 at 10:50
0

When optimized, both codes are likely to perform identically. However, they are not equivalent (at least in the C language family). In these languages, true is simply one of many nonzero integers. However, if the "boolean" happens to be any other nonzero integer, the comparison will fail even though the "boolean" is true. Here is an example in C:

Foo* makeFoo();

int main() {
    Foo* myFoo = makeFoo();
    if(myFoo) {
        printf("Successfully created a Foo object.\n");
    }
    // The following doesn't work, because true is just the number 1, and you can't place an object at that address.
    if(myFoo == true) {
        printf("You will never see this!\n");
    }
}
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106