Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Method invocation vs using a variable

Recently I got into a discussion with my Team lead about using temp variables vs calling getter methods. I was of the opinion for a long time that, if I know that I was going to have to call a simple getter method quite a number of times, I would put it into a temp variable and then use that variable instead. I thought that this would be a better both in terms of style and performance. However, my lead pointed out that in Java 4 and newer editions, this was not true somewhat. He is a believer of using a smaller variable space, so he told me that calling getter methods had a very negligible performance hit as opposed to using a temp variable, and hence using getters was better. However, I am not totally convinced by his argument. What do you guys think?

like image 659
Seagull Avatar asked Dec 17 '09 18:12

Seagull


People also ask

What is the difference between method and variable in Java?

A function is a bunch of code, which can be executed, if you call. But a function can be a variable, too, as it stores data and values, too. See the following syntax: var functionname = function(){} . A method is a function of an object.

How do you call a method using variables?

You could try something like: Method m = obj. getClass(). getMethod("methodName" + MyVar); m.

What does invocation mean in Java?

An invocation is a request that has been prepared and is ready for execution. Invocations provide a generic (command) interface that enables a separation of concerns between the creator and the submitter.


2 Answers

Never code for performance, always code for readability. Let the compiler do the work.

They can improve the compiler/runtime to run good code faster and suddenly your "Fast" code is actually slowing the system down.

Java compiler & runtime optimizations seem to address more common/readable code first, so your "Optimized" code is more likely to be de-optimized at a later time than code that was just written cleanly.

Note:

This answer is referring to Java code "Tricks" like the question referenced, not bad programming that might raise the level of loops from an O(N) to an O(N^2). Generally write clean, DRY code and wait for an operation to take noticeably too long before fixing it. You will almost never reach this point unless you are a game designer.

like image 121
Bill K Avatar answered Sep 19 '22 17:09

Bill K


Your lead is correct. In modern versions of the VM, simple getters that return a private field are inlined, meaning the performance overhead of a method call doesn't exist.

like image 34
Randolpho Avatar answered Sep 19 '22 17:09

Randolpho