dotixx dotixx - 1 month ago 13
C# Question

Local variables or class fields?

I read today a post about performance improvement in C# and Java.

I still stuck on this one:




19. Do not overuse instance variables

Performance can be improved by using local variables. The code in example 1 will execute faster than the code in Example 2.

Example1:

public void loop() {
int j = 0;
for ( int i = 0; i<250000;i++){
j = j + 1;
}
}


Example 2:

int i;
public void loop() {
int j = 0;
for (i = 0; i<250000;i++){
j = j + 1;
}
}





Indeed, I do not understand why it should be faster to instantiate some memory and release it every time a call to the
loop
function is done when I could do a simple access to a field.

It's pure curiosity, I'm not trying to put the variable 'i' in the class' scope :p
Is that true that's faster to use local variables? Or maybe just in some case?

Answer
  1. Stack faster then Heap.

    void f()
    {
        int x = 123; // <- located in stack
    }
    
    int x; // <- located in heap
    void f()
    {
        x = 123  
    }
    
  2. Do not forget the principle of locality data. Local data should be better cached in CPU cache. If the data are close, they will loaded entirely into the CPU cache, and the CPU does not have to get them from memory.

Comments