Static Method in Instances

125 Views Asked by At

Straight up question: If I run code analysis, it tells me to make methods static even in nonstatic classes. As far as I know, static methods are JITed and run on the Type-Object in the Heap. So wouldn't make a method static in a non static class mean, that the instance has to search the type object in the Heap and run the method there?

Wouldn't that mean a performance issue? Sure it would not be that big of a deal, but I'd still be interested on this.

3

There are 3 best solutions below

2
On BEST ANSWER

No, it doesn't work like that.

A static method is actually (imperceptibly) more efficient than a non-static one because (a) it does not have a hidden "this" pointer passed to it and (b) because it's static, the framework doesn't have to do anything about it being virtual (although that last point also applies to non-virtual member methods too, of course).

Here is an in-depth article about CLR runtime type handling. In particular, look at the information there about the MethodTable and the Method Slot Table.

Here's another good article from Joe Duffy. It doesn't explicitly talk about static methods, but it does explain how method calls are made at the lowest (assembler) level, so you would be able to see why a static method call is efficient.

0
On

Good post about performance comparsion of static methods vs instance methods: Performance of static methods vs instance methods

TLDR:

  • Mostly the performance costs of instance vs static are below negligible.
  • 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.

  • 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.

2
On

I think the point is that you're not calling a static method upon an instance, but on the class itself. Any method that does not directly rely on instance information could (and based upon code analysis also should) be marked static and then be called like this:

NonstaticClass.TheStaticMethod();

instead if this

NonstaticClass inst = new NonstaticClass();
inst.TheStaticMethod();

This is because less overhead is required to look up and run a static method than a non-static method on a class instance.