Is it a form of premature pessimization to check for equality prior to assignment when applied to primitive types?

Viewed 206

Having code that often modifies a non-local (member) variable (in a single threaded scenario, using primitive types), is it premature pessimization to just assign without checking whether necessary (considering that the modification of state has no other side effects as indicated in the code below)?

e.g:

static int someState = 0;
void foo(int newState)
{
  /* Which is better? This...*/
  someState = newState; /*Assign regardless*/

  /* ... or this... */
  if (someState != newState)
  {
    someState = newState; /*Only write when required*/ 
  }
}

I always feel the check is superfluous and would like to hear your opinions.

  • Does the speed between reading and writing vary drastically to the point of considering the read check when the state change is made often?
  • Is the extra check highly contextual?

I might profile this, yes, but I'm wondering about community consensus concerning something like this. I mostly just perform the assignment regardless, and I'm wondering whether this is how its done mostly.

4 Answers
Related