shrini1000
shrini1000

Reputation: 7226

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).

Upvotes: 9

Views: 1674

Answers (2)

user949300
user949300

Reputation: 15729

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.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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).

Upvotes: 9

Related Questions