5

Assume you have quite long method with around 200 lines of very time sensitive code. Is it possible that extracting some parts of code to separate methods will slow down execution?

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63

4 Answers4

1

Most probably, you'll get a speedup. The problem is that optimizing a 200 lines beast is hard. Actually, Hotspot gives it up when the method is too long. Once I achieved a speedup factor of 2 by simply splitting a long method.

Short methods are fine, and they'll be inlined as needed. So the method call overhead gets minimized. By inlining, Hotspot may re-create your original method (improbable due to its excessive length) or create multiple methods, where some of them may contain code not present in the original method.

The answer is "yes, it may get slower." The problem is that the chosen inlining may be suboptimal. However, it's very improbable, and I'd expect a speedup instead.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
0

The overhead is negligible, the compiler will inline the methods to execute them.

EDIT:

similar question

Community
  • 1
  • 1
MarcioB
  • 1,538
  • 1
  • 9
  • 11
0

I don't think so.
Yes some calls would be added and some stackframes but that doesn't cost a lot of time and depending on your compiler it might even optimize the code in such a way that there is basically no difference in the version with one method compared to the one with many.
The loss of readability and reusability you would get by implementing all in one method is definitely not worth the (if at all existing) performance increase.

Ch33f
  • 609
  • 8
  • 17
0

It is important that the factored out methods will be either declared private or final. The just in time compiler in the JVM will then inline everything, which means there will be a single big method executed as result.

However, always benchmark your code, when modifying it.

cruftex
  • 5,545
  • 2
  • 20
  • 36
  • See this for a rebuttal of the idea that `final` helps performance: https://www.ibm.com/developerworks/java/library/j-jtp1029/index.html – slim Nov 29 '17 at 10:00