Several months ago I was having a discussion (that’s a polite word for argument) with a few co-workers about the optimal length of methods and the topic of performance came up.
Someone with a C++ background brought up the point that shorter methods were less efficient than longer ones due to the extra cost of more V-Table lookups.
At the time, I countered that the performance differences were surely minimal and that the trade-off was justifiable when taking into account the maintainability benefits of shorter methods (increased readability, decreased chance of bugs, etc.).
However, I recently discovered while reading a chapter in Bill Wagner’s Effective C# book that this seemingly common-sense assertion about the way method length affects performance is not necessarily true in the .NET world.
In order to amortize the startup cost over the life of an application, the CLR compiles code on a method by method basis the first time it is used.
The ultimate result is that longer methods may slow down an application by requiring code to be prematurely compiled before it is actually used.
Consider the following example:
Regardless of what parameter is passed to the method, all 100+ lines of code will have to be JIT compiled the first time the method is used.
Now consider this refactored version:
The first time this version of the method is called, the JIT compilation process will be faster because only half as many lines of code need to be compiled.
If true is passed in to this method as a parameter then the CLR will compile everything under the DoCrazyShit method, but will delay compiling the DoRelativelyTameStuff method until the DoFunStuff method is called with a false parameter.
Reducing the number of lines of code that need to be compiled is not the only benefit of shorter methods.
Small, simple methods also facilitate the use of other performance boosting techniques like enregistration (storing variables in the register instead of on the stack) and method inlining (substituting method calls for the implementation).
The moral of the story? Keep the JIT compiler, impatient users, and fellow developers who have to maintain your crap after you retire to some tropical island happy. Keep your methods short!