Vishrant
Vishrant

Reputation: 16628

Does loading thousands of class in JVM impact performance on method execution

I have created a Bean lets say

com.session.implementation.MathOperationBean

and in that MathOperationBean lets say there are method add.

Now in my current company it is required to create one more such Bean file (its a long story so can not explain here why one more Bean is required) lets call that Bean as

com.v1_0.session.implementation.MathOperationBean // (package is different)

Just for your information v1_0 is a version number.

So the number of Bean files are double with double the number of methods. And there will be thousands of bean files for both the version which will be loaded in JVM.

My question is: Does loading these many bean files in JVM reduce the performance of method execution in those beans?

Upvotes: 2

Views: 1534

Answers (1)

dimo414
dimo414

Reputation: 48794

Broadly speaking, no.

The JVM is very lazy, and will avoid loading or executing unused code paths. So if you have a thousand classes on your classpath but your application only uses ten of them you won't see (much of) an improvement by explicitly limiting your classpath to the ten used classes. Generally it's safe to let the JVM figure out what it needs; it's probably smarter than you.

You can experiment with this easily enough - add some libraries with lots of classes to your classpath and re-run your application. You should see no difference in performance.

More to the point there is no relationship between the efficiency of calling a specific method and the number of classes loaded by the JVM. In the same way that a hashtable remains O(1) regardless of how large it is, there should be (effectively) no impact on execution time based on the number of classes being loaded.

As @EJP points out there is a system-wide cost to applications that use more memory, but this cost is sub-linear (both the OS and the JVM will optimize where possible) so it's not something I'd spend a lot of time worrying about unless you have reason to believe it's a bottleneck.

There's nothing particularly special about versioned packages; by the sound of it there's still a fixed number of classes being loaded for each bean, meaning there's at most a fixed overhead per method invocation.

As the commentators point out there are code-quality issues with the package structure you're describing, but performance is not likely to be a huge issue.

Upvotes: 1

Related Questions