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.
The primary reason has to do with how JIT compilation works, which is another round of compilation that occurs at runtime in order to transform code from IL to machine language.
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:
1: public void DoFunStuff(bool isBossPresent)
2: {
3: if (isBossPresent)
4: {
5: //do 50 lines worth of crazy shit inline
6: }
7: else
8: {
9: //do 50 lines of tamer stuff
10: }
11: }
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:
1: public void DoFunStuff(bool isBossPresent)
2: {
3: if (isBossPresent)
4: {
5: DoCrazyShit();
6: }
7: else
8: {
9: DoRelativelyTameStuff();
10: }
11: }
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!
Popularity: 4% [?]