Search code examples
javastaticinstanceinstance-variables

Performance difference between static and instance variables


An instance variable is one per Object, every object has its own copy of instance variable.

A static variable is one per Class, every object of that class shares the same Static variable.

class MyStaticClass{
  private static int myStaticInt;

  public static int getMyStaticInt() {return myStaticInt;}
}

class MyInstanceClass{
  private int myNonStaticInt;

  public int getMyNonStaticInt() {return myNonStaticInt;}
}

Is there a performance difference between either? Is it more expensive to call one over the other?

int i = MyStaticClass.getMyStaticInt();

OR:

int i = new MyInstanceClass().getMyNonStaticInt();

Solution

  • It's not a matter of performance. static and instance variables have a different purpose.

    Using

    int i = new MyInstatnceClass().getMyNonStaticInt();
    

    is almost certainly useless, since each time you call new MyInstatnceClass() you create a new MyInstatnceClass instance, having a new myNonStaticInt instance variable. Since you are not keep a reference to the created instance, you cannot retrieve the same instance variable twice, which makes it useless.

    If you need a single copy of a variable to be shared across all instances of the class, static variable is the way to go.

    That said, the latter call is also more expansive, since it involves creation and initialization of an instance of your MyInstatnceClass class (in addition to loading and initialzing the class if it's the first access that class).

    On the other hand, MyStaticClass.getMyStaticInt() only loads and initializes the class MyStaticClass if it's the first access of that class. It doesn't have to create any instance of that class.