Let's say I have some time critical code that's run many times from a certain class. However, this code needs to process data encapsulated in another class, so my two options are either get a reference to the data and perform the computation in my original class, or delegate the computation to the class that stores it and return the results. My question is, does calling a method on another class and getting a result come with a performance penalty compared to just getting a reference of data and using a method within the same class ? And if so would this be of practical significance or is it just like 1-2 milliseconds ?
- 31-2ms is eons of time for a computer. If that is your frame of reference, you won't have to think about optimizations at all.Keppil– Keppil2015-01-17 23:50:30 +00:00Commented Jan 17, 2015 at 23:50
- profile it, there is no other meaningful answer.OMGtechy– OMGtechy2015-01-17 23:53:51 +00:00Commented Jan 17, 2015 at 23:53
- My guess is that it would be less than a millisecond penalty which may be reduced to no penalty at all overtime by JVM optimizations. However I'm not an expert. JMV is very complex beast, processors are complex beasts and it may even drill down to cache line alignment. Maybe in some rare cases it may make noticeable difference.NiematojakTomasz– NiematojakTomasz2015-01-17 23:54:13 +00:00Commented Jan 17, 2015 at 23:54
2 Answers
I think you should not even think about this. This is all up to JVM and jit compiling optimizations. And they are getting better.
I believe short methods can even be compiled and executed inline (that is JVM may not even generate a call instruction)
Better focus on writing optimal code in your critical functions.
3 Comments
My question is, does calling a method on another class and getting a result come with a performance penalty compared to just getting a reference of data and using a method within the same class ?
It won't be in the "long run".
If this piece of code is criticial, it means the JIT will eagerly look for ways to optimize it at runtime, and one of the first optimizations it will perform is inlining.
Of course, this is if the given piece of code is not a 60+k bytecode-long monster...
FWIW, HotSpot, (Oracle's implementation) will start and optimize as soon/late as 10 000 executions of a same piece of code. Other JVM implementations may have their JIT kick in sooner or later than that.