Is if(var == true) faster than if(var != false)?(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) 快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:if(var == true) 是否比 if(var != false) 快?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01