开发者

Performance: assign boolean value always or check value first?

开发者 https://www.devze.com 2023-02-02 11:21 出处:网络
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?

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


For a field, just set it. For a property, it could be more complex, depending on whether the get or set is disproportionately expensive, and/or whether the set checks this internally (bypassing events etc).

As a general rule for properties, just set it, until you know this to be an issue due to profiling.

For fields; don't worry excessively about it; default to just set.


Back in the 90s when I did program in x86 assembler, the rule was (IIRC) to avoid jumps. An if statement would have been implemented as a jump.

So my conclusion would be (under the assumtion that at least some of those ancient rules still apply) that avoiding the if and assigning directly would be more performant.


What I normally do is if I am expecting something other then the default value for any type of variable I set it to something it normally wouldn't be. This way if the value didn't change, then I know what to expect and how to handle it. It wouldn't really be appliciable to your examples, your question is sort of vague, your examples don't explain what your attempting to do.

I agree with Marc's and Dan's statements of course.

0

精彩评论

暂无评论...
验证码 换一张
取 消