Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Premature optimization in Java: when to use "x = foo.getX()" vs simply "foo.getX()"

When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?

I'm sure the answer of course is "it depends".

I'm more concerned about the simpler case where the getter is simply a "pass-along-the-value-of-a-private-variable" type method. i.e. there's no expensive computation involved, no database connections being consumed, etc.

My question of "is it better" pertains to both code readability (style) and also performance. i.e. is it that much of a performance hit to have:

SomeMethod1(a, b, foo.getX(), c);
SomeMethod2(b, foo.getX(), c);
SomeMethod3(foo.getX());

vs:

X x = foo.getX();
SomeMethod1(a, b, x, c);
SomeMethod2(b, x, c);
SomeMethod3(x);

I realize this question is a bit nit-picky and gray. But I just realized, I have no consistent way of evaluating these trade-offs, at all. Am fishing for some criteria that are more than just completely whimsical.

Thanks.

like image 332
Aaron Fi Avatar asked Aug 31 '10 19:08

Aaron Fi


1 Answers

The choice shouldn't really be about performance hit but about code readability.

When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
And it's really better to read:

String username = user.getName();
SomeMethod1(a, b, username, c);
SomeMethod2(b, username, c);
SomeMethod3(username);

than

SomeMethod1(a, b, user.getName(), c);
SomeMethod2(b, user.getName(), c);
SomeMethod3(user.getName());
like image 169
Colin Hebert Avatar answered Oct 03 '22 13:10

Colin Hebert