性能:总是分配布尔值还是先检查值? [英] Performance: assign boolean value always or check value first?

查看:30
本文介绍了性能:总是分配布尔值还是先检查值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定它可以忽略不计,但考虑到我想从方法中将 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

这篇关于性能:总是分配布尔值还是先检查值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆