Alex Rivera | Logout

Performance: assign boolean value always or check value first?

Asked 2011-01-03T17:40:31.190
27

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;
Edit
Report

1 Answer

23

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
answered 2011-01-03T17:47:15.933

Your Answer