Performance of Static Methods VS Instance Methods

Performance of static methods vs instance methods

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

Static Vs Instance Method Performance C#

Your first link states:

Thats because static methods are using
locks to be Thread-safe. The always do
internally a Monitor.Enter() and
Monitor.exit() to ensure Thread-safety

That is utterly, horribly, abominably wrong.



If you add [MethodImpl(MethodImplOptions.Synchronized)] to the method, that statement becomes partially true.

Adding this attribute will cause the CLR to wrap static methods inside lock(typeof(YourClass)) and instance methods inside of lock(this).

This should be avoided where possible


Your second link is correct.

Static methods are a little bit faster than instance methods, because they don't have a this parameter (thus skipping a NullReferenceException check from the callvirt instruction)

Performance of using static methods vs instantiating the class containing the methods

From here, a static call is 4 to 5 times faster than constructing an instance every time you call an instance method. However, we're still only talking about tens of nanoseconds per call, so you're unlikely to notice any benefit unless you have really tight loops calling a method millions of times, and you could get the same benefit by constructing a single instance outside that loop and reusing it.

Since you'd have to change every call site to use the newly static method, you're probably better spending your time on gradually refactoring.

static method vs instance method, multi threading, performance

Methods are code - there's no problem with thread accessing that code concurrently since the code isn't modified by running it; it's a read-only resource (jitter aside). What needs to be handled carefully in multi-threaded situations is access to data concurrently (and more specifically, when modifying that data is a possibility). Whether a method is static or an instance method has nothing to do with whether or not it needs to ne serialized in some way to make it threadsafe.

performance of static vs non static method for an utility class

One final thing to add to what people have said here.

Using a static method has a slightly less overhead due to the fact that you have guaranteed compile time binding. Static method calls will create the bytecode instruction invokestatic. ]

In a typical scenario, instance methods are bound at runtime, and will create the bytecode instruction invokevirtual which has higher overhead than invokestatic.

However, this only becomes relevant in the case of likely millions of iterations, and i would caution against this driving your class design. Do what makes sense from a design perspective. Based on your description, static methods are probably the way to go. In fact, this is relatively standard practice to create a utility class:

public class MyUtilities {
private MyUtilities() { } // don't let anyone construct it.
public static String foo(String s) { ... }
}

Static class vs Class with constructor performance

Technically yes, the static method will be slightly faster per call, because a static method doesn't have to check and see if the object it's attached to (because it's not) has been instantiated. This happens behind the scenes. (Technically there will be other slight overhead to set up the object etc.)

This is not a really good reason under most circumstances to choose one over the other though. They have different purposes. The a static method can't maintain state of internal variables like an object can etc.

In your case I would probably pick the static method. Based on the code you show, you don't have a real need to maintain a reference to the object you want to do something to. Perform a function on it, and be done with it.

With the other approach you have to create an object, then call the method. Furthermore the way it's set up, you have to instantiate a new object for each target object you have to perform the action on, because there is a reference stored in a private variable the method acts on. To me this would be more confusing from a readability perspective.

Speed Static Methods vs Class Method

Test it. This is going to be an implementation detail of whichever Python interpreter (and version of said interpreter) you happen to be running. For my interpreter (Python 3.5, Windows, 64 bit):

>>> class Foo:
... @classmethod
... def bar(cls):
... pass
... @staticmethod
... def baz():
... pass
...
>>> import timeit
>>> min(timeit.repeat('Foo.bar()', 'from __main__ import Foo', repeat=5, number=100000))
0.02093224880448102
>>> min(timeit.repeat('Foo.baz()', 'from __main__ import Foo', repeat=5, number=100000))
0.017951558014670965
>>> min(timeit.repeat('f.bar()', 'from __main__ import Foo; f = Foo()', repeat=5, number=100000))
0.020720195652103257
>>> min(timeit.repeat('f.baz()', 'from __main__ import Foo; f = Foo()', repeat=5, number=100000))
0.017714758216740734

It looks like staticmethod is slightly faster (likely just because it doesn't need to pass an argument into the function at all), but we're talking about a difference of 3 milliseconds for 100,000 calls, which is nanoseconds per call in cost.

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();  //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.



Related Topics



Leave a reply



Submit