Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the StackOverflow platform developers use static methods for performance?

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?

like image 710
Juan Carlos Coto Avatar asked Nov 26 '14 16:11

Juan Carlos Coto


2 Answers

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.

like image 83
Thomas Weller Avatar answered Nov 18 '22 10:11

Thomas Weller


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;
    }
}
like image 45
oleksii Avatar answered Nov 18 '22 11:11

oleksii