性能:始终分配布尔值或先检查值? [英] Performance: assign boolean value always or check value first?

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

问题描述

我敢肯定,这是微不足道的,但因为我想从一个方法中指定来一个布尔字段,这是否选择有什么区别?如果是这样,为什么?

 字段= TRUE; //可能已经是事实,但我不在乎
 

 如果字段= TRUE(场!);
 

解决方案

我会说不。但是,这不依赖于一个事实,即我们真的在谈论的字段的,而不是一个的属性的,它的可以(虽然它绝对不应该)表现出不同的行为在你包括两个片段(即,如果没有与在吸气剂的副作用)的逻辑。

更新:如果你在谈论的性能开销,几乎没有任何difference- 但是我相信任务是不断所谓价格稍微低一些(比读值)。下面是一个示例程序来证明这一点:

 布尔B = FALSE;

秒表SW = Stopwatch.StartNew();
的for(int i = 0; I< int.MaxValue ++ I)
{
    B =真实;
}
sw.Stop();

时间跨度setNoCheckTime = sw.Elapsed;

SW = Stopwatch.StartNew();
的for(int i = 0; I< int.MaxValue ++ I)
{
    //这部分将不会指派,为b将永远是正确的。
    如果(!B)
    {
        B =真实;
    }
}
sw.Stop();

时间跨度checkSetTime = sw.Elapsed;

Console.WriteLine(分配:{0}毫秒,setNoCheckTime.TotalMilliseconds);
Console.WriteLine(读:{0}毫秒,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天全站免登陆