Dib
Dib

Reputation: 2083

Is checking a property value before setting, and setting only if different, quicker or slower than setting blindly?

Please can anyone advise me if in C#.Net it is more performant to check a property value before setting, and only set if the value differs, or is it more performant to just blindly set it to the new value?

For example:

bool newActiveState = true;

// Only set the value if it differs
if(myObject.IsActive != newActiveState )
{
     myObject.IsActive = newActiveState;
}

versus

bool newActiveState = true;

// Set it blindly
myObject.IsActive = newActiveState;

Does one way help the compiler better than the other? Does one way give a better compiler hint?

I am aware that if there is any gain it will only be a micro-optimisation, but in a massive nested recursive loop it may be handy to know.

Update based upon clarification question by ~Adam Houldsworth:

Assuming it is just a plain property and no code runs on setting, but later code reads the property value and only performs time consuming processes then, so not in the scope of this code.

Upvotes: 1

Views: 1138

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133995

Based on your clarification, that no other code is executed as a direct result of setting the property, then there's no benefit to doing the check.

To look at it in more detail, consider your code:

if (myObject.IsActive != newActiveState)
{
    myObject.IsActive = newActiveState;
}

Obviously, if the values are not equal and you end up setting the value, then the total amount of work the CPU did is more than if it just set the value blindly. That is, it had to do the check and set the variable.

If the values are equal, then it has to check and branch around the set.

So

  • if a check-and-branch is faster than a write
  • and the amount of time saved in the check-and-branch makes up for the extra write time
  • then the conditional could be faster

You'd have to do some analysis to determine how often the value is set vs. not set, and use that analysis to determine the total amount of time taken for each of the two cases. You could then come up with an average time for that bit of code, based on your expected ratio of sets/branches. You could then compare that number with the total time taken for the same number of blind writes.

I'll save you the trouble, though. If there is a difference between the branch and the blind write, it's going to be very, very small. Probably fractions of a microsecond. The write is going to be fast because the memory location being written to is already in the CPU's cache. Whatever the difference (if any) between the branch and the write, it's not going to make up for the extra cost of the conditional test.

Upvotes: 1

Related Questions