Performance: assign boolean value always or check value first?(性能:总是分配布尔值还是先检查值?)
问题描述
我确定它可以忽略不计,但考虑到我想从方法中将 true
分配给布尔字段,这个选择有什么不同吗?如果有,为什么?
字段=真;//可能已经是真的了,但我不在乎
对
if(!field) field = true;
解决方案我会说不.但这确实取决于我们真正谈论的是 field 而不是 property,这 可能(尽管它绝对不应该) 在您包含的两个片段中表现出不同的行为(即,如果在 getter 中存在具有副作用的逻辑).
更新:如果您谈论的是性能开销,实际上并没有什么区别——但是我相信分配的开销要小得多(比阅读价值).下面是一个示例程序来演示这一点:
bool b = false;秒表 sw = Stopwatch.StartNew();for (int i = 0; i < int.MaxValue; ++i){b = 真;}sw.Stop();TimeSpan setNoCheckTime = sw.Elapsed;sw = 秒表.StartNew();for (int i = 0; i < int.MaxValue; ++i){//这部分永远不会赋值,因为 b 永远为真.如果 (!b){b = 真;}}sw.Stop();TimeSpan checkSetTime = sw.Elapsed;Console.WriteLine("分配:{0} ms", setNoCheckTime.TotalMilliseconds);Console.WriteLine("读取:{0} ms", checkSetTime.TotalMilliseconds);
我的机器上的输出:
<上一页>分配:2749.6285 毫秒读取:4543.0343 毫秒
I'm sure it is negligible, but given that I want to assign true
to a boolean field from within a method, does this choice make any difference? If so, why?
field = true; // could already be true, but I don't care
versus
if(!field) field = true;
I'd say no. But this does depend on the fact that we really are talking about a field as opposed to a property, which may (though it definitely should not) exhibit different behavior in the two snippets you included (i.e., if there is logic with side effects in the getter).
Update: If you're talking about performance overhead, there is practically no difference—but I believe assignment is ever-so-slightly less expensive (than reading the value). Here is a sample program to demonstrate this:
bool b = false;
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < int.MaxValue; ++i)
{
b = true;
}
sw.Stop();
TimeSpan setNoCheckTime = sw.Elapsed;
sw = Stopwatch.StartNew();
for (int i = 0; i < int.MaxValue; ++i)
{
// This part will never assign, as b will always be true.
if (!b)
{
b = true;
}
}
sw.Stop();
TimeSpan checkSetTime = sw.Elapsed;
Console.WriteLine("Assignment: {0} ms", setNoCheckTime.TotalMilliseconds);
Console.WriteLine("Read: {0} ms", checkSetTime.TotalMilliseconds);
Output on my machine:
Assignment: 2749.6285 ms Read: 4543.0343 ms
这篇关于性能:总是分配布尔值还是先检查值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:性能:总是分配布尔值还是先检查值?


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