Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's static/instance variables operation performance

While reading Jack Shirazi's 'Java performance tuning', I came across the following statement:

"Instance and static variables can be up to an order of magnitude slower to operate on when compared to method arguments and local variables."

Is this still applicable to Java 6/7? And if yes, what are the reasons behind it? (He explained something about having special bytecodes for accessing local variables/parameters but I did not understand it).

like image 324
shrini1000 Avatar asked Feb 03 '23 10:02

shrini1000


2 Answers

The key words here are can be. The issue is that locals and params (which are essentially a flavor of locals) may be in registers, while instance and static variables will ultimately end up in memory (they would get into registers for the time necessary to operate on them, but eventually back to the memory they go).

like image 168
Sergey Kalinichenko Avatar answered Feb 12 '23 08:02

Sergey Kalinichenko


Even if access were 10 times slower, it would only matter if you were in a very long loop. And the Java Memory Model is pretty smart (sometime "too" smart) about optimizing memory access to instance variables. If you use an instance var in a long loop, say, to sum 100,000 doubles, the JVM is very likely to optimize that access and, in fact, not write the result to memory every single time. The exception being volatile fields. In fact, this whole optimization issue is why there are volatile fields.

like image 27
user949300 Avatar answered Feb 12 '23 08:02

user949300