Skip to content Skip to sidebar Skip to footer

Does @staticmethod Save Any Ram In Cpython Or Micropython?

When answering a recent question I repeated my assumption that one reason for using @staticmethod was to save ram, since a static method was only ever instantised once. This asser

Solution 1:

Methods do not get "instantiated", they get bound – that is a fancy word for "their self/cls parameter is filled", similar to partial parameter binding. The entire point of staticmethod is that there is no self/cls parameter and thus no binding is needed.

In fact, fetching a staticmethod does nothing at all - it just returns the function unchanged:

>>> classTest:
...     @staticmethod... asyncdefmeth1():
... await asyncio.sleep(10)
... return78
...
>>> Test.meth1
<function __main__.Test.meth1()>

Since methods are bound on-demand, they don't usually exist in their bound form. As such, there is no memory cost to pay for just having methods and nothing for staticmethod to recoup. Since staticmethod is an actual layer during lookup¹ – even if it does nothing – there is no performance gain either way from (not) using staticmethod.

In [40]: classTest:
    ...:     @staticmethod
    ...:     defs_method():
    ...:         pass
    ...:     defi_method(self):
    ...:         pass
    ...: 

In [41]: %timeit Test.s_method
42.1 ns ± 0.576 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [42]: %timeit Test.i_method
40.9 ns ± 0.202 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Note that these timings may vary slightly depending on the implementation and test setup. The takeaway is that both approaches are comparably fast and performance is not relevant to choose one over the other.


¹staticmethod works as descriptor that runs everytime the method is looked up.

Post a Comment for "Does @staticmethod Save Any Ram In Cpython Or Micropython?"