I've been reading about the StackExchange technology (for example, this article about SO performance on highavailability.com), and have noticed they mention heavy usage of static methods for better performance.
Why do static methods perform better? I would think reduction in garbage collection costs has something to do with it (since no instances are needed for static methods); however, is there something more?
The main reason has to do with the call stack. While instance methods always have the this
pointer as first parameters, static methods don't have that overhead.
It's only milliseconds (or even only fractions thereof on a fast system), but it can add up in performance-critical systems.
Why do static methods perform better?
I don't think they do. Perhaps there is some gain in GC time if data that is passed to the static method and returned from it leaves on stack. In this case it's not tracked by GC.
I ran a program and got different results for my 3 attempts, two times static method was slightly faster, 1 time (shown below) instance method was faster. All data within reasonable deviation range. So my conclusion: there is no noticeable difference if disregarding GC.
t1 = 8.0055 ms (instance)
t2 = 8.0119 ms (static)
Here is a quick test program
public class Program
{
const int innerMax = 100;
const int outerMax = 1000;
public static void Main()
{
var t1 = new TimeSpan();
var t2 = new TimeSpan();
var program = new Program();
for (int i = 0; i < outerMax; i++)
t1 = program.InstanceAction();
for (int i = 0; i < outerMax; i++)
t2 = StaticAction();
Console.WriteLine("t1 = {0} ms (instance)", t1.TotalMilliseconds);
Console.WriteLine("t2 = {0} ms (static)", t2.TotalMilliseconds);
Console.ReadLine();
}
private TimeSpan InstanceAction()
{
return Time(() => {
var sw = new SpinWait();
for (int i = 0; i < max; i++)
sw.SpinOnce();
});
}
private static TimeSpan StaticAction()
{
return Time(() => {
var sw = new SpinWait();
for (int i = 0; i < innerMax; i++)
sw.SpinOnce();
});
}
private static TimeSpan Time(Action action)
{
Stopwatch stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.Elapsed;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With