Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Is if(var == true) faster than if(var != false)?

Pretty simple question. I know it would probably be a tiny optimization, but eventually you'll use enough if statements for it to matter.

EDIT: Thank you to those of you who have provided answers.

To those of you who feel a need to bash me, know that curiosity and a thirst for knowledge do not translate to stupidity.

And many thanks to all of those who provided constructive criticism. I had no knowledge of the ability to state if(var) until now. I'm pretty sure I'll be using it now. ;)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First off: the only way to answer performance question is to measure it. Try it yourself and you'll find out.

As for what the compiler does: I remind you that "if" is just a conditional goto. When you have

if (x)
   Y();
else
   Z();
Q();

the compiler generates that as either:

evaluate x
branch to LABEL1 if result was false
call Y
branch to LABEL2
LABEL1:
call Z
LABEL2:
call Q

or

evaluate !x
branch to LABEL1 if result was true

depending on whether it is easier to generate the code to elicit the "normal" or "inverted" result for whatever "x" happens to be. For example, if you have if (a<=b) it might be easier to generate it as (if !(a>b)). Or vice versa; it depends on the details of the exact code being compiled.

Regardless, I suspect you have bigger fish to fry. If you care about performance, use a profiler and find the slowest thing and then fix that. It makes no sense whatsoever to be worried about nanosecond optimizations when you probably are wasting entire milliseconds somewhere else in your program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...