Why are explicit calls to magic methods slower than “sugared” syntax?

笑着哭i 提交于 2019-11-30 05:07:25

Two reasons:

  • The API lookups look at the type only. They don't look at self.foo.__hash__, they look for type(self.foo).__hash__. That's one less dictionary to look in.

  • The C slot lookup is faster than the pure-Python attribute lookup (which will use __getattribute__); instead looking up the method objects (including the descriptor binding) is done entirely in C, bypassing __getattribute__.

So you'd have to cache the type(self._foo).__hash__ lookup locally, and even then the call would not be as fast as from C code. Just stick to the standard library functions if speed is at a premium.

Another reason to avoid calling the magic methods directly is that the comparison operators do more than just call one magic method; the methods have reflected versions too; for x < y, if x.__lt__ isn't defined or x.__lt__(y) returns the NotImplemented singleton, y.__gt__(x) is consulted as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!