152

My question is relating to the performance characteristics of static methods vs instance methods and their scalability. Assume for this scenario that all class definitions are in a single assembly and that multiple discrete pointer types are required.

Consider:

public sealed class InstanceClass
{
      public int DoOperation1(string input)
      {
          // Some operation.
      }

      public int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more instance methods.
}

public static class StaticClass
{
      public static int DoOperation1(string input)
      {
          // Some operation.
      }

      public static int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more static methods.
}

The above classes represent a helper style pattern.

In an instance class, resolving the instance method take a moment to do as oppose to StaticClass.

My questions are:

  1. When keeping state is not a concern (no fields or properties are required), is it always better to use a static class?

  2. Where there is a considerable number of these static class definitions (say 100 for example, with a number of static methods each) will this affect execution performance or memory consumption negatively as compared with the same number of instance class definitions?

  3. When another method within the same instance class is called, does the instance resolution still occur? For example using the [this] keyword like this.DoOperation2("abc") from within DoOperation1 of the same instance.

9
  • what do you mean by "instance resolution"? On the IL level, "this" pointer is available just as any other local variable. In fact, on some old CLR/JIT versions, you could call an instance-method on a NULL providing it did not touch the 'this' - the code just flied through and crashed on nothing.. now CLR/JIT contains explicit null-check on every member invoke.. Commented Sep 5, 2012 at 10:45
  • > vijaymukhi.com/documents/books/ilbook/chap8.htm and 'call instance' versus just 'call'. The former expects 'this' parameter and the latter - doesnt. Commented Sep 5, 2012 at 10:53
  • @Quetzalcoatl sorry for the confusion, the question was more method to method from the same instance and if that requires the instance to be resolved to itself. Commented Sep 5, 2012 at 10:53
  • 1
    @quetzalcoatl I assumed he meant, "does the compiler get rid of checking that this points to something when a class calls an instance method on itself?"
    – Jon Hanna
    Commented Sep 5, 2012 at 13:57

3 Answers 3

204

In theory, a static method should perform slightly better than an instance method, all other things being equal, because of the extra hidden this parameter.

In practice, this makes so little difference that it'll be hidden in the noise of various compiler decisions. (Hence two people could "prove" one better than the other with disagreeing results). Not least since the this is normally passed in a register and is often in that register to begin with.

This last point means that in theory, we should expect a static method that takes an object as a parameter and does something with it to be slightly less good than the equivalent as an instance on that same object. Again though, the difference is so slight that if you tried to measure it you'd probably end up measuring some other compiler decision. (Especially since the likelihood if that reference being in a register the whole time is quite high too).

The real performance differences will come down to whether you've artificially got objects in memory to do something that should naturally be static, or you're tangling up chains of object-passing in complicated ways to do what should naturally be instance.

Hence for number 1. When keeping state isn't a concern, it's always better to be static, because that's what static is for. It's not a performance concern, though there is an overall rule of playing nicely with compiler optimisations - it's more likely that someone went to the effort of optimising cases that come up with normal use than those which come up with strange use.

Number 2. Makes no difference. There's a certain amount of per-class cost for each member it terms of both how much metadata there is, how much code there is in the actual DLL or EXE file, and how much jitted code there'll be. This is the same whether it's instance or static.

With item 3, this is as this does. However note:

  1. The this parameter is passed in a particular register. When calling an instance method within the same class, it'll likely be in that register already (unless it was stashed and the register used for some reason) and hence there is no action required to set the this to what it needs to be set to. This applies to a certain extent to e.g. the first two parameters to the method being the first two parameters of a call it makes.

  2. Since it'll be clear that this isn't null, this may be used to optimise calls in some cases.

  3. Since it'll be clear that this isn't null, this may make inlined method calls more efficient again, as the code produced to fake the method call can omit some null-checks it might need anyway.

  4. That said, null checks are cheap!

It is worth noting that generic static methods acting on an object, rather than instance methods, can reduce some of the costs discussed at http://joeduffyblog.com/2011/10/23/on-generics-and-some-of-the-associated-overheads/ in the case where that given static isn't called for a given type. As he puts it "As an aside, it turns out that extension methods are a great way to make generic abstractions more pay-for-play."

However, note that this relates only to the instantiation of other types used by the method, that don't otherwise exist. As such, it really doesn't apply to a lot of cases (some other instance method used that type, some other code somewhere else used that type).

Summary:

  1. Mostly the performance costs of instance vs static are below negligible.
  2. What costs there are will generally come where you abuse static for instance or vice-versa. If you don't make it part of your decision between static and instance, you are more likely to get the correct result.
  3. There are rare cases where static generic methods in another type result in fewer types being created, than instance generic methods, that can make it sometimes have a small benefit to turn rarely used (and "rarely" refers to which types it's used with in the lifetime of the application, not how often it's called). Once you get what he's talking about in that article you'll see that it's 100% irrelevant to most static-vs-instance decisions anyway. Edit: And it mostly only has that cost with ngen, not with jitted code.

Edit: A note on just how cheap null-checks are (which I claimed above). Most null-checks in .NET don't check for null at all, rather they continue what they were going to do with the assumption that it'll work, and if a access exception happens it gets turned into a NullReferenceException. As such, mostly when conceptually the C# code involves a null-check because it's accessing an instance member, the cost if it succeeds is actually zero. An exception would be some inlined calls, (because they want to behave as if they called an instance member) and they just hit a field to trigger the same behaviour, so they are also very cheap, and they can still often be left out anyway (e.g. if the first step in the method involved accessing a field as it was).

6
  • Can you comment on whether the static vs instance question has any bearing on cache coherence? Is reliance on one or the other more likely to cause cache misses? Is there a good outline explaining why? Commented Jun 23, 2015 at 18:51
  • @scriptocalypse Not really. The instruction cache won't see any difference, and at that level there isn't much difference between accessing data via this or via an explicit parameter. A bigger impact here would be how close data is to related data (value-type fields or array values are closer than data in reference type fields) and patterns of access.
    – Jon Hanna
    Commented Jun 23, 2015 at 19:18
  • "in theory, we should expect a static method that takes an object as a parameter and does something with it to be slightly less good than the equivalent as an instance on that same object. "-- Do you mean that if above sample method takes parameter as object instead of string, non-static is better? for example: I have my static method takes object as parameter and serializes it into string and returns string. are you suggesting to use non-static in this case?
    – Emil
    Commented May 8, 2017 at 16:01
  • 1
    @batmaci I mean there's a good chance obj.DoSomehting(2) would be slightly cheaper than DoSomething(obj, 2) but as I also said the difference is so slight and so dependent on tiny things that might end up different in final compilation that it's not really worth worrying about at all. If you're doing something as expensive (relative to the sort of differences in play here) as serialising something to a string then it's especially pointless.
    – Jon Hanna
    Commented May 9, 2017 at 1:52
  • 1
    There's one, perhaps obvious, yet important thing missing in this otherwise excellent answer: an instance method requires an instance, and creating an instance is not cheap. Even a default ctor still requires initialization of all fields. Once you have an instance already, this answer applies ("all other things being equal"). Of course, an expensive cctor can make static methods slow as well, but that's only on the first call an applies to instance methods equally. See also learn.microsoft.com/en-us/previous-versions/dotnet/articles/…
    – Abel
    Commented Jan 7, 2020 at 8:49
15

When keeping state is not a concern (no fields or properties are required), is it always better to use a static class?

I would say, yes. As declaring something static you declare an intent of stateless execution (it's not mandatory, but an intent of something one would expect)

Where there is a considerable number of these static classes (say 100 for instance, with a number of static methods each) will this affect execution performance or memory consumption negatively as compared with the same number of instance classes?

Don't think so, unless you're sure that static classes are really stateless, cause if not it's easy mess up memory allocations and get memory leaks.

When the [this] keyword is used to call another method within the same instance class, does the instance resolution still occur?

Not sure, about this point (this is a purely implementation detail of CLR), but think yes.

3
  • Static methods can't be mocked, If you do TDD or even just unit testing this will hurt your tests a lot.
    – trampster
    Commented Mar 24, 2017 at 10:33
  • @trampster Why? It's just a piece of logic. You can easily mock what you give it? To get correct behavior. And lot of static methods will be private pieces of logic in a function anyway.
    – M. Mimpen
    Commented Oct 8, 2018 at 15:18
  • @M.Mimpen as long as you leave it to small private pieces your fine, if its a public method and you use it from other closes and need to change what it does in your test then your stuck, things like file IO or database access or network calls etc, if put in static method will become unmockable, unless like you say you inject a mockable dependency as a parameter to the static method
    – trampster
    Commented Oct 9, 2018 at 2:28
0

Static methods are faster but less OOP. If you'll be using design patterns, static method is likely bad code. Business logic are better written as non-Static. Common functions like file reading, WebRequest etc are better as static. Your questions have no universal answer.

2
  • 25
    You given no arguments to your claims.
    – ymajoros
    Commented Sep 5, 2012 at 11:12
  • 2
    There are arguments in here 1. instance is likely better for design patterns & business logic, and 2. static is likely better for file reading, web requests
    – rupweb
    Commented Sep 22, 2020 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.