Tuesday 28 September 2010

C# .net method call performance

I’ve recently been in a conversation with another dev about a code base and had an alarming exchange regarding method calls and performance.

Alarming because he claimed that the reason that the methods in the system were so long was because someone higher in the dev chain 'tech lead' or 'architect' had claimed that it was expensive to make method calls???

I’ve seen my fair share of long methods, awful things that destroy reuse, developer productivity, and introduce many, many tangled bugs. These usually evolve because the devs are under pressure to get things out of the door on tight schedules, or by inexperienced devs who unfortunately don’t know much better. Personally I like to try and keep my methods short <20 lines, to keep to the principal that a method should only do one thing, do it clearly and well (so its easy to read, understand and change), you know all the usual stuff. But I’ve never seen the justification for long methods to be because of performance...

so i thought what is this performance gain of long methods? After googling around I didn’t find anything (if you do let me know) so i wrote a program.

Essentially it consisted of 2 loops, one to do a simple calculation in line and one to call a method to do the same calculation.

for (int i = 0; i < LoopCount; i++ )
{
fakeCalculationVariable++;
}


for (int i = 0; i < LoopCount; i++ )
{
Calculate();
}

i took timings before and after each loop and recorded the results

LoopCount= 100000000
elapsed time = 234.447 milliseconds
elapsed time = 640.8218 milliseconds
Method call loop took 406.3748 millisecs longer than inline loop for 100000000 calls
Thats a cost of 0.0000041 millisecs per method call

i wasn’t sure about the results so i decided to run it again, this time with ten billion iterations of the loop, these performance penalties must show up with that many calls.

LoopCount= 1000000000
elapsed time = 2250.6912 milliseconds
elapsed time = 6376.9584 milliseconds
Method call loop took 4126.2672 millisecs longer than inline loop for 1000000000 calls
Thats a cost of 0.0000041 millisecs per method call

its quite conclusive, method calls don’t really add up to all that much overhead, as we all expected.

No comments:

Post a Comment