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
这篇关于性能:总是分配布尔值还是先检查值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:性能:总是分配布尔值还是先检查值?
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
