4 ms·
how does the runtime performance of super() compare to the hardcoding method? (from your example, using dict.__setitem__ as opposed to super().__setitem__ )
by veyron 15y ago
how does the runtime performance of super() compare to the hardcoding method? (from your example, using dict.__setitem__ as opposed to super().__setitem__ )
- alextp 15y agoI don't think it suffers much as the method resolution order (mro) is computed ahead-of-time when creating the class.
- veyron 15y agoso super() is computed ahead of time? That doesn't make sense when you look at his comment: "The calculation depends on both the class where super is called and on the instance’s tree of ancestors." I agree that the class's MRO can be computed ahead of time, but theoretically the instance's order could be different (if a class method changed the definition of __setitem__)
- alextp 15y agoThe method resolution order for instances of the same class is always the same for all methods. If the class doesn't implement that method, the interpreter just skips and goes to the next place in the call chain. All super does is call the next method in the chain. So if you have class A(object), class B(A), class C(A), and class D(B, C), the MRO of D's instances will be B C A object. Each time an instance of D calls super, it will call the next method in the chain, not necessarily B's or C's or A's, even if the call to super is in B's method. This is why super() receives the class as a parameter, so it can know from when in the object's mro to start looking up the next method.
- veyron 15y ago"This is why super() receives the class as a parameter" <-- this is not necessary in python 3. Your argument is valid in python2, but python3 allows a super() call without a type argument. From the docs: "super(type[, object-or-type])" <-- python2 doc, type is required "super([type[, object-or-type]])" <-- type is optional in python3
- raymondh 15y agoIn CPython, calling super() has about the same cost as calling any other builtin like len() or int(). The MRO itself is precomputed and stored in inst.__class__.__mro__. Contrasting dict.__setitem__ with super().__setitem__, the latter adds one function call. In addition, both forms require a builtin lookup and an attribute lookup. In PyPy, much of the overhead of builtin lookups, function calls, and attribute lookups is automatically optimized away.
- kingkilr 15y agoUnfortunately on PyPy super is less efficient than refering directly to the parent classes method, however it's fixable (and will be fixed).