user4159962
user4159962

Reputation:

Is there a performance penalty for calling method on another object instead of own?

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 ?

Upvotes: 0

Views: 133

Answers (2)

fge
fge

Reputation: 121710

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.

Upvotes: 1

yurgis
yurgis

Reputation: 4067

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.

Upvotes: 1

Related Questions