Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed Static Methods vs Class Method

Is there any speed difference between class Methods and Static Methods? I am aware of the different use cases, but sometimes i could completely get rid of a class method and would like to know speed differences

like image 516
user1767754 Avatar asked May 26 '16 23:05

user1767754


1 Answers

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.

like image 110
ShadowRanger Avatar answered Sep 28 '22 18:09

ShadowRanger