During a recent code review a colleague suggested that, for class with 4 int properties, assigning each to zero in the constructor would result in a performance penalty.
For example,
public Example()
{
this.major = 0;
this.minor = 0;
this.revision = 0;
this.build = 0;
}
His point was that this is redundant as they will be set to zero by default and you are introducing overhead by essentially performing the same task twice. My point was that the performance hit would be negligible if one existed at all and this is more readable (there are several constructors) as the intention of the state of the object after calling this constructor is very clear.
What do you think? Is there a performance gain worth caring about here?
I don’t believe they’re the same operation, and there is a performance difference. Here’s a microbenchmark to show it:
Results:
Now, would that make me change the code? Absolutely not. Write the most readable code first. If it’s more readable with the assignment, keep the assignment there. Even though a microbenchmark shows it has a cost, that’s still a small cost in the context of doing any real work. Even though the proportional difference is high, it’s still creating a billion instances in 8 seconds in the “slow” route. My guess is that there’s actually some sort of optimization for completely-empty constructors chaining directly to the completely empty
object()constructor. The difference between assigning to two fields and only assigning to one field is much smaller.In terms of while the compiler can’t optimize it out, bear in mind that a base constructor could be modifying the value by reflection, or perhaps a virtual method call. The compiler could potentially notice those, but it seems a strange optimization.