Question

I was told by a colleague that in Java, the performance may be worse if we create more methods, stacking many methods calling over them in JVM, specially in a Java EE environment.

This seems to somewhat defeat the concept of object oriented programming. Like if we write long methods - what isn't good for code readability - we can achieve more performance due to less methods in JVM stack.

So, write many methods who call and interact with each other is worse to performance than write a few long methods to use less stacks in JVM? Is this is a correct affirmation?

Was it helpful?

Solution

It's probabbly an wrong assumption, first as common sense nested calls shouldn't have any (measurable) performance hit at all. After doing some research you'll find that the JVM can do some optimizations in your code "automagically":

Adaptive Optimization

And more importantly:

Inline Expansion

As you can see:

In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the callee

So probabbly, if you as programmer can say "hey, one big method is better than nesting tons of other methods", the JIT/JVM/javac can figure that for you and fix it >>IF<< it's worth.

I think that unless you get some numeric statistics, you are fine with tons of methods instead a monolithic piece of software.

OTHER TIPS

The JVM have this thing called JIT, which would optimize the application's code with various techniques.

One of those is called "inline optimization". In this particular optimization, the JIT will automatically inline methods when needed, so, you might lost some processor cycles in this particular instant, even if it does, it's not sufficient to justify this kind of argument in my opinion.

It's always nice to remember that usually the performance hotspots are the I/O and database access. Also nice to remember that, nowadays, machine time is cheap and developer's time are expensive.

Further reading:

As others said, in Java its generally better to use lot of short methods, because they are JITed and inlined better.

But it's plausible that in EE enviroment situation can be different. At least for method that are not simply called, but there is aditional overhead because of 1) Transaction handling, 2) Interceptors 3) EJB remote calls (stay away from highly granual remote calls)

But if you split large method into multiple private methods, these overheads should not happen.

tl,dr: Method call itself is not problem, additional overhead is (and you have controll over it)

PS: I would not even consider NOT splitting methods for performance reasons untill proven there actually is some performance problem. With clearer code you usually achieve better performance, because you much easier identify parts that are 1) not actually needed 2) are called multiple times with same result

Licensed under: CC-BY-SA with attribution
scroll top