if(var == true)是否比if(var!= false)更快? [英] Is if(var == true) faster than if(var != false)?

查看:660
本文介绍了if(var == true)是否比if(var!= false)更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单的问题。我知道它可能只是一个很小的优化,但最终你会使用足够的if语句来解决它。

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

编辑:谢谢那些已经提供的人答案。

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.

非常感谢所有提出建设性批评的人。到目前为止,我还不知道是否(var)。我漂亮确定我现在会使用它。 ;)

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. ;)

推荐答案

首先:回答性能问题的唯一方法是测量它。自己尝试一下,你就会发现。

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

关于编译器的作用:我提醒你if只是一个条件goto。当你有

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();

编译器将其生成为:

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

evaluate !x
branch to LABEL1 if result was true

取决于是否更容易生成代码以引出x恰好是正常或反转结果。例如,如果您有 if(a< = b),则可能更容易将其生成为(如果!(a> b))。或相反亦然;这取决于正在编译的确切代码的细节。

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.

这篇关于if(var == true)是否比if(var!= false)更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆