C#’s string library provides an excellent case study in the cost of adding additional method calls to simple library code. In the section on the built-in string APIs String.StartsWith and String.EndsWith, it was mentioned that hand-coded replacements are 10–100 times faster than the built-in methods, even when unwanted locale coercion was suppressed.
The key reason for this performance difference is simply the cost of adding additional method calls to tight inner loops. Each method that is invoked must locate the address of the method in memory and push another frame onto the stack. Neither of these operations are free, but in most code they are sufficiently small to ignore.
However, when running small methods in tight loops, the overhead added by introducing additional method calls can become significant – and even dominant.
Consider the following two simple methods.
Example 1:
int Accum { get; set; }
Accum = 0;
for(int i = 0; i < myList.Count; i++) {
Accum += myList[i];
}
Example 2:
int accum = 0;
int len = myList.Count;
for(int i = 0; i < len; i++) {
accum += myList[i];
}
Both methods calculate the sum of all integers in a C# generic List<int>. The first example is a bit more “modern C#” in that it uses an automatically generated property to hold its data values.
While on the surface these two pieces of code appear equivalent, the difference is notable when the code is analyzed for method calls.
Example 1:
int Accum { get; set; }
Accum = 0;
for(int i = 0;
i < myList.Count; // call to List::getCount
i++) {
Accum // call to set_Accum
+= // call to get_Accum
myList[i]; // call to List::get_Value
}
So there are four method calls each time the loop executes:
myList.Count invokes the get method on the Count propertyget and set methods on the Accum property must be calledget to retrieve the current value of Accum so that it can be passed to the addition operationset to assign the result of the addition operation to AccumExample 2:
int accum = 0;
int len = myList.Count;
for(int i = 0;
i < len;
i++) {
accum += myList[i]; // call to List::get_Value
}