Program-Me-Rev
Program-Me-Rev

Reputation: 6634

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();

Upvotes: 2

Views: 1853

Answers (2)

errantlinguist
errantlinguist

Reputation: 3828

Since instance methods can be polymorphically overridden, a very naive JVM implementation must at least initially use a virtual mehod table to find the appropriate method to call. Classes themselves, however are not polymorphic and class methods cannot be overridden. Due to this, they have a simpler lookup mechanism.

However, real-world JVMs are incredibly smart and can tell which methods are never overridden and optimize this lookup away. In other words, in all but the most contrived instances with non-existent JVMs will there be a difference in performance. Instead, use static methods to represent functionalities relevant to the entire class of objects itself rather than to a single instance thereof.

Upvotes: 2

Eran
Eran

Reputation: 394106

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.

Upvotes: 3

Related Questions