10

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Juan Carlos Coto
  • 11,900
  • 22
  • 62
  • 102
  • Even the bit about garbage collection being linked to heavy use of static methods is specifically mentioned in the same article. However that seems to be the only detail. – BoltClock Nov 26 '14 at 16:49
  • 1
    In today's world of 3-GHZ+ multi-core servers, I doubt there's much time saved; however, a static variable is "always" there and "always" addressable. If they are used correctly that are a good thing! – JWP Nov 26 '14 at 16:53
  • 1
    Static methods don't require a runtime check to ensure that the object the method belongs to is non-null. Any checks like this are performed at compile-time. – helrich Nov 26 '14 at 16:53
  • 2
    If you're creating object instances just to pass information to the static methods as parameters, then you're not gaining anything; you're writing C-style code that OOP is designed to emulate and make easier syntactically, without being functionally much different. If they're *not* creating objects to pass information around, then the methods are conceptually static (as they're not associated with any state) and there is no reason for them to have been instance methods in the first place. – Servy Nov 26 '14 at 16:53
  • possible duplicate of [What is better? Static methods OR Instance methods](http://stackoverflow.com/questions/874363/what-is-better-static-methods-or-instance-methods) – random Nov 26 '14 at 16:54
  • 1
    They've been obsessive about getting rid of GC delays. Which sometimes caused an SO user to have to wait for several seconds for a page update instead of 50 msec. I know they had trouble dealing with the unpredictability of GC.RegisterForFullGCNotification(). So they probably went the other way, keeping a fixed working set with lots of static data that just mutates but doesn't change size. Getting static methods out of that is a given. Maybe not what they would have done if .NET 4.5 would have been available. – Hans Passant Nov 26 '14 at 18:57
  • @Hans I’m not sure that “static data size” in any way implies “static methods”. helrich’s remark about the lack of a runtime check for null seems much more relevant in this context. – Konrad Rudolph Dec 30 '14 at 14:58

3 Answers3

2

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.

Thomas Weller
  • 11,631
  • 3
  • 26
  • 34
  • 1
    If the information contained in the implicit reference is actually needed, then making them method static simply means requiring it to be *explicit* instead, meaning no real savings. If it isn't needed (i.e. the method used no instance state) then it should have been static from the start as it's not conceptually tied to an instance of the object. – Servy Nov 26 '14 at 16:56
  • Not to mention, depending on how your class structure is designed, it conveys the message that no instance members are used by this method. That, (and things like `readonly` and `sealed` where relevant) conveys extra information to the next developer, which can help them make decisions on how to approach something or debug the code. – Adam Houldsworth Nov 26 '14 at 16:56
  • See Raymon Chen's [When does an object become available for garbage collection?](http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx), "An object can become eligible for collection during execution of a method on that very object." – dcastro Nov 26 '14 at 17:10
  • 1
    It's highly unlikely that they were worried about the microseconds difference that is *sometimes* associated with instance methods. – Jim Mischel Dec 05 '14 at 19:08
1

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;
    }
}
oleksii
  • 35,458
  • 16
  • 93
  • 163
  • Why... would you disregard GC? That's the top reason static "performs better". It's not about the time for one call, but the system responsiveness you get from avoiding gc pauses – Brian White May 28 '17 at 16:49
-1

Heavy usage of static classes and methods, for simplicity and better performance

Where the real performance benefits are related to concrete system setup and concrete metrics done for concrete business domain, the simplicity of using static classes and methods, where it's possible, derives from:

1) clear manifestation of "execution only" flow in static method

2) easy unit test, as you are dealing only with execution artifact (static function)

3) the state and execution are distinct and separate values, therefore there are no "hidden state" issues (static non immutable vars usually a sign of a bad design), or small amount of them otherwise.

Overall, code is easier to manage, test and possibly understand.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    I agree with you in each and every case. But the question was about performance, not about conceptual clarity. – Thomas Weller Nov 26 '14 at 17:12
  • There are small performance benefits in using statics, or non using properties but fields, but, again, it depends on concrete case and concrete measurements. – Tigran Nov 26 '14 at 17:20
  • 1
    Easy unit tests? If a method calls SomeDataProvider.getLatestData() then that's a hard compile time binding that you can't replace for tests. You'll go insane trying to unit test that codebase. If you instead use dependency injection to get a DataProvider then you can mock it and easily test. .... this is very, very, very widely-held commonly-understood wisdom. – Rag Dec 20 '14 at 03:22
  • @BrianGordon: any code practice can be handled bad or right, the same is valid of DI. Speaking about static methods simplicity, I mean having "execution only", or stateless execution artifacts, that can be easily tested, as they are not biased to any state by any means. That is a point of my answer. Otherwise, everyone is free to write the code as he wants. – Tigran Dec 20 '14 at 14:35