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
这篇关于性能:总是分配布尔值还是先检查值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:性能:总是分配布尔值还是先检查值?


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01