Why does overloading ++ take significantly longer than incrementing just the value?

  • A+

Why does incrementing an (in my case) Uint by one 100.000.000 times take ~0.175 seconds, while incrementing an Uint within a struct the same amount of times takes ~1.21 seconds?

The tests have been conducted roughly 10 times with nearly the same results in time. If it can't be helped, so be it. But I would like to know what causes this. The time increase is rather significant. The operator overload below is the exact code used:

private uint _num;         public static Seq operator ++(Seq a) {     a._num++; return a; } 

I chose to edit the instance itself (if this goes against guidelines) rather than returning a new instance because this also takes quite a while longer.

This struct will be incremented very frequently, thus I'm looking for the reason to this increased processing time.


It's simply a matter of how smart the jitter is. For a regular local int variable, the statement


can in many cases be reduced to a single machine instruction because the local variable could be enregistered. If it is not enregistered then the sequence of instructions will be to load the value, increment it, and store it, so a handful of instructions.

But overloading ++ on a struct has the following semantics. Suppose we have our struct in s and we say s++. That means effectively that we implement

s = S.operator++(s); 

What does that do?

  1. Make a copy from s to the local variable location that is the new formal parameter
  2. Stores away any register state that is going to be overwritten by the callee
  3. execute the call instruction
  4. load the value of the formal, increment it, store it
  5. copy the new value to the location reserved for the return value
  6. execute the return instruction
  7. restore the state of the previous activation frame

  8. copy the returned value to the location for s.

So your fast program is doing step 4. Your slow program is doing steps 1 through 8, and is about eight times slower. The jitter could identify that this is a candidate for inlining and get rid of some of those costs, but it is by no means required to, and there are plenty of reasons why it might choose not to inline. The jitter does not know that this increment is important to you.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: