JavaDeveloper
JavaDeveloper

Reputation: 5660

Accessing instance variable or local var

Wanted to know the if it is better to access an instance variable Or store its value locally. For example:

Method1:

while (ctr < arr.length ) {
   sysout(arr[ctr++]);
}

vs

Method2:

int length = arr.length
while (ctr < length) {
   sysout(arr[ctr++];
} 

Looks like Method1 is cleaner as it does not need any extra variable declaration. Is there any benefit in this case for using method 2?

To make the question generic what are the best practices in this case?

Thanks,

Upvotes: 0

Views: 74

Answers (2)

fge
fge

Reputation: 121692

Answer: it does not matter.

Either the compiler will compile it to the exact same bytecode (which, in this situation, is likely), or the JIT will kick it at runtime and make both these solutions equivalent.

Your primary objective when doing Java is doing code which is obviously correct. Let the compiler and JIT handle performance.

Upvotes: 5

AllTooSir
AllTooSir

Reputation: 49352

I guess the second approach is ever-so-slightly faster because in the second case the run time will not have to perform a arr.length each time in the loop . However the difference is very insignificant . Since the length property of an array is like its public final member, so fetching that length is a constant time operation. It would have been different case if you had done list.size().

Upvotes: 1

Related Questions