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

查看:32
本文介绍了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.

非常感谢所有提供建设性批评的人.直到现在我才知道声明 if(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"只是一个条件跳转.当你有

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),则可能更容易将其生成为 (if !(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天全站免登陆