Efficiency on Loops Using Class Variables

  • Thread starter Thread starter Robert Linder
  • Start date Start date
R

Robert Linder

Efficiency on Loops Using Class Variables

I have a loop that has a large loop e.g.System.Math.Pow( 2, 20).
I check a local variable against a class variable inside this loop.
// if ( localVariable > classVariable ){}

Does .Net perform better(faster) if I assign the class variable to a
local variable?
// double localVariable2 = classVariable
// for (){
// if ( localVariable > localVariable2 ){}
// }
 
Robert Linder said:
Efficiency on Loops Using Class Variables

I have a loop that has a large loop e.g.System.Math.Pow( 2, 20).
I check a local variable against a class variable inside this loop.
// if ( localVariable > classVariable ){}

Does .Net perform better(faster) if I assign the class variable to a
local variable?
// double localVariable2 = classVariable
// for (){
// if ( localVariable > localVariable2 ){}
// }

It may do. As ever, I would test with real world data to see if the
performance benefit is worth the slight loss of readability though.
 
HI Robert,

I don't think so. I think the performance should be the same.
If you want to be sure you might check the IL code produced by compiler and
also machine code that runs on specific procesor.
However, even the same IL code could produce different machine instructions
on different procesors.
 
I don't think so. I think the performance should be the same.

Not necessarily. The JIT compiler can stick the local variable in a
register, but it'll need to go to main memory every time to get the
instance value.
 
Hi Jon,

Jon Skeet said:
Not necessarily. The JIT compiler can stick the local variable in a
register, but it'll need to go to main memory every time to get the
instance value.

Yes, I know it is not necessarily. But even if the values is not in the
register it would be in processor's cache (yes, it is slower but not that
much).
And you can't never be sure also, there is just too many factors involved.
 
Yes, I know it is not necessarily. But even if the values is not in the
register it would be in processor's cache (yes, it is slower but not that
much).
And you can't never be sure also, there is just too many factors involved.

You're right, you can't be sure - which is why saying that the
performance should be the same is a dangerous claim, IMO.

The difference would probably be negligible in most cases, but just
occasionally it could be significant.
 
Back
Top