3

In Java, we only store one copy of the static method into memory, and we can call it over and over again. This is for performance and space saving.

Previously, someone had claimed in work that static function in Python does not work the same way as in Java, is this correct?

Someone also claimed that every time we are calling the Python static method, and Python Interpreter still need to spend the time to instantiate an object first. Is this correct?

class A(object): @staticmethod def static_1(): print 'i am static' 
2
  • 1
    Shouldn't be any slower than a regular method. Commented Apr 24, 2018 at 3:28
  • @staticmethod is a decorator, implying the method is wrapped. The extra function call (if there is one) might have some overhead, although perhaps not significant (depends on your definition of significant). Commented Apr 24, 2018 at 4:04

3 Answers 3

4

The Python method for java static method is @classmethod.

Sign up to request clarification or add additional context in comments.

1 Comment

Someone claimed to me that static method in Python is slow, and I was looking for some answer at the interpreter level.
1

Accessing a Python static method does not involve creating a new object. Python just returns the original function object.

(Accessing a non-static method does involve creating a new method object, but this is cheap. In particular, it only bundles together a reference to the function and a reference to self; it does not involve copying the function.)

1 Comment

Also, even "copying the function" would be cheap. A function is just a struct with a few tuples and a code object, so it's basically copying (and increfing, for CPython) a handful of pointers to immutable objects. Many people new to Python think it must involve recompiling the source or something…
0

There is a difference between Python the language and specific Python implementation.

Also, almost all the languages store only one copy of method each method in memory. This applies to all static, class and regular method. The savings you mentioned come from not needing to pass the pointer to 'self' in Python or 'this' in Java. One less parameter to pass could add to huge savings for the methods that are called from within innermost long running loops.

As for storing methods themselves. Implementations like PyPi constantly perform JIT to compile methods into machine code. They keep recompiling based on updated statistics on how method performs. I believe similar behaviour occurs in Java.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.