Enrichman
Enrichman

Reputation: 11337

Is adding lots of methods going to decrease performance?

I know that use a method instead of doing everything line after line is much more clear, so let's just put this assumption apart.

I was asking myself if doing the same thing calling a method take more time (for the call to the method) or not, imagining that the bytecode generated is the same.

Upvotes: 1

Views: 244

Answers (4)

Mike Dunlavey
Mike Dunlavey

Reputation: 40679

Sure it's a good idea to modularize the code, and it shouldn't make a noticeable difference in performance.

Except. It could very well make a big difference, for a reason having to do not with technology, but with Human Nature.

It's natural to look at lines like

a = b + c;

and

Foo(bar);

and think they cost about the same, which they might, but probably don't.

The problem is, methods are magnets for additional code, including additional method calls.

Then what I find when doing performance tuning is I grab stack samples, and it's not unusual for them to be 20-30 levels deep. If I examine each call on a stack sample, nearly every one makes perfect sense.

Nearly.

All it takes is one not-really-necessary call out of those 20-30 to completely blow performance. If I see such a thing on as few as two(2) stack samples, I know I've found a big opportunity for optimization. For example, if I take three samples and see that on two of them, the fraction of time that could be saved is in the vicinity of 2/3. Put another way, the speedup factor could be in the range of three times.

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

1. Your argument is right up to certain limit, as calling a method results into the creation of a Runtime Stack, which contains the line of the executing code, the local variables, the program counter, and if its non-static then "this" too.

2. But this wont create any impact with the HighSpeed processors, and Powerful IDEs.

3. Moreover if you are not using the methods, then it would be Violation of DRY Principle(Dont Repeat Yourself), which states that one should keep all the Information and Behaviours in a Single Sensible Place.

Upvotes: 2

Hans Z
Hans Z

Reputation: 4744

Theoretically, yes, for the most part, you are creating a new stack frame to carry out the calculations. Practically, no you're pretty much not gonna notice the performance hit. A full discussion of this question is a bit more complicated and it has to do with under the hood performance of the generated byte code and machine/virtual machine it is running on.

Upvotes: 5

ewein
ewein

Reputation: 2735

Well serial programs (step by step) are faster than running methods because you have to spend time scanning the code finding the method and running it. However this time is to small to make any impact on performance.

Upvotes: 1

Related Questions