Why is local variable access faster than class member access in Python?

后端 未结 2 1885
半阙折子戏
半阙折子戏 2020-12-03 14:29

While trying to tackle a more complex problem, I came to compare access speed to local variable vs member variables.

Here a test program:

#!/usr/bin/         


        
2条回答
  •  悲&欢浪女
    2020-12-03 14:43

    Local names is faster because Python does some optimization that local names don't need dict access, on the other hand, instance attributes need to access the __dict__ of the object.

    This is also the reason why local names are faster than global names.

提交回复
热议问题