JavaDeveloper
JavaDeveloper

Reputation: 5660

Use local variable vs access instance variable

Assume a scenario where we can use a local variable vs access an instance variable what should I chose ?

eg: inside foo.java

int x = bar.getX();
int y = x * 5;

Advantage is that we dont have performance impact of accessing object variable over and over.

or inside foo.java

int y = bar.getX() * 5;

Advantage of using the second method, is we dont need to create and maintain another variable.

Upvotes: 0

Views: 116

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

Thumb rule is reduce the scope of variable as much as you can.

If you want access of variable across all the methods, use instance member. Otherwise simply go for local variable.

If you are using your variable X across methods, define it as a member.

Coming to the performance impact , int x = obj.getX(); simply you are creating a copy variable and nothing else.

You'll realize once you use the Object and not the primitive. Then reference matters.

So in your case the first line int x = obj.getX(); is little redundant. Second is more readable.

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88378

Do whatever is more readable.

Usually the shorter code is easier to read, comprehend, and show correct, but if an expression becomes long and the itermediate expressions make sense on their own, then introduce a local variable to make the code clearer.

As far as performance goes, you don't know that there will be any performance hit one way or the other unless you profile the code. Optimization in Java happens at compile but also at runtime with modern JIT compliation. Compilers can do inlining, common subexpression elimination and all kinds of algebraic transformations and strength reductions that I doubt that your example will show any performance impact one way or the other.

And unless an expression like this is executed a billion times or more in a loop, readability wins.

Upvotes: 3

Related Questions