Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the comparison with true shows a lack of understanding by your partner. Bools should be named things to avoid this (such as isAvailable: if (isAvailable) {...}).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...