I always feel bad when people arrive at this site and do not find what they where looking for. That is why I implemented this little series called “Questions and Answers” or “Answering Questions nobody asked me since 1777”. Most of these Questions are based on search terms over which users arrived at this site (a little creepy or nice and helpful? Who is to say) and some I got via email (if you too have a programming questions feel free to send me an email via the contact button above). So lets get right to it:

“does declaring a static variable in java kill the performance?”

The short answer: No.

Now for the long answer:

When static variables decrease java performance

Technically static variables may in some situations lower performance.

Static variables are stored in the memory, while non-static local variables may be stored in the registers. If you are new to computer science this might not tell you much, so you might want to read up on it. What is important regarding performance is that it is a lot faster to operate on registers directly than it is to load values from memory first.

In practice though this barely matters in most situations.

When static variables increase java performance

In some other situations the performance can benefit from making a variable static.

If the initialization of the variable takes a lot of computing power and the variable is used more than once in different instances it makes a lot of sense to make that variable static (just remember to surround the actual initialization code with a static block as well). An example of this might be an array holding some fixed information. In many of these cases though the singleton pattern might be a better fit.

java static variables and memory

If you are thinking of memory performance, the same as the above for the computing performance holds: If a variable is used by many instances of an object and the variable holds fixed data making it static is useful as it only has to be held in memory once. But in all other cases it just wastes memory.

Summary: Do static variables kill java performance?

to summarize:

Except in very few cases making a variable static does not really matter performance wise.

But except in very few cases static variables are considered bad style in java.

Objections, thoughts, in-depth explanations and general geeky knowitallism are welcome in the comments :)