Python | Why is accessing instance attribute slower than local?

前端 未结 3 1239
傲寒
傲寒 2020-12-17 23:13
import timeit

class Hello():
    def __init__(self):
        self.x = 5
    def get_local_attr(self):
        x = self.x
        # 10x10
        x;x;x;x;x;x;x;x;x;x         


        
3条回答
  •  清酒与你
    2020-12-17 23:38

    You've run into scoping issue which is pretty detailed-ly explained here

    Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

    • the innermost scope, which is searched first, contains the local names
    • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
    • the next-to-last scope contains the current module’s global names
    • the outermost scope (searched last) is the namespace containing built-in names

    So accessing local variables is 1 lookup less than instance variable and stacked against so many repetitions it works slower.

    This question is also a possible duplicate of this one

提交回复
热议问题