Performance of Static Methods VS. Functions

Class methods VS Class static functions VS Simple functions - Performance-wise?

At CPU level, there is only one kind of function, and it very much ressemble the C kind. You could craft your own, but...

As it turns out, C++ being built with efficiency in mind maps most functions directly to call instructions:

  • a namespace level function is like a regular C function
  • a static method is like a namespace level function (from a call point of view)
  • a non-static method is very similar to a static method, except an implicit this parameter is passed on top of the other parameters (one pointer)

All those 3 have the exact same kind of performance.

On the other hand, virtual methods have a slight overhead. There was a C++ technical report on performance which estimated the overhead compared to a non-virtual method between 10% and 15% (from memory) for empty functions. Meaning that for any function with meat inside (ie, doing real work), the overhead itself is close to getting lost in the noise. The real cost comes from the inhibition of inlining unless the virtual call can be deduced at compile-time.

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

Is static method faster than non-static?

You should always use static when you don't need an object around you method, and use dynamic when you need an object. In the example you provides, you don't need an object, because the method doesn't interact with any properties or fields in your class.

This one should be static, because it doesn't need an object:

class Person {
public static function GetPersonByID($id) {
//run SQL query here
$res = new Person();
$res->name = $sql["name"];
//fill in the object
return $res;
}
}

This one should be dynamic, because it uses the object it is in:

class Person {
public $Name;
public $Age;
public function HaveBirthday() {
$Age++;
}
}

The speed diffirence is minimal, but you have to create an object to run dynamic methods, and that object is saved in memory, so dynamic methods use more memory and a little more time.

static functions vs normal class function

Under the hood a static function differs from an instance function only in how it takes its implicit parameters: instance functions take one implicit parameter for self, while static functions take no implicit parameters for anything.

As far as the code for the function is concerned, there is no penalty for a function being static or non-static. Same goes for performance: static functions are simplest lightweight "packages" of executable code; calling them carries no additional costs.

Your particular implementation, however, may benefit from storing activityIndicator in a variable to avoid re-creating it in each static call. Moreover, this would make it easier for you to remove the activity indicator from superview once the activity has finished. If you would like to use a single activityIndicator, you could keep your function static, and add a class variable for activityIndicator. Otherwise, you should make multiple instances of ActivityIndicator class, each having its own activityIndicator instance variable. In this case, startActivityIndicator should become an instance method as well.

Javascript static methods vs prototypal/instatiated methods on performance

Edit: So there is a bit of a performance difference when you are instantiating the class vs. calling the "static" version, but the difference doesn't really warrant you making any changes to your code (premature optimization) unless you are seeing an actual slow down.

As demonstrated in the basic jsperf test I setup, there really isn't much of a difference, performance wise. You should make the decision based on whether or not you want the context (this) to refer to your base class or not.

Big performance difference between using class with static functions vs instantiated class?

According uber AS3 optimiser Jackson Dunstan there is a significant difference, with static methods being about 3 to 4 times slower than non-static methods.

  • Static vs. non-static
  • Why static is slow

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.

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.

Do C# static functions perform better than nonstatic functions, beyond reduced memory usage?

From Static Classes and Static Class Members (C# Programming Guide)

A call to a static method generates a
call instruction in Microsoft
intermediate language (MSIL), whereas
a call to an instance method generates
a callvirt instruction, which also
checks for a null object references.
However, most of the time the
performance difference between the two
is not significant.



Related Topics



Leave a reply



Submit