Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 592
dotixx Avatar asked Jul 17 '13 15:07

dotixx


People also ask

What is the difference between a local variable and a field?

A local variable is defined within the scope of a block. It cannot be used outside of that block. I cannot use local outside of that if block. An instance field, or field, is a variable that's bound to the object itself.

What is an example of a local variable?

For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

Is it better to use local or global variables?

It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.


2 Answers

  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.

like image 97
oakio Avatar answered Sep 21 '22 05:09

oakio


The performance is down to the number of steps required to get the variable. Local variable addresses are known at compile time (they are a known offset on the stack), to access a member you load the object 'this' to get the address of the actual object, before you can get the address of the member variable.

like image 29
StuPointerException Avatar answered Sep 21 '22 05:09

StuPointerException