Time difference in accessing instance variables

in this code there is time delay in accessing variable via self.value and accessing it via a local variable why there is a time difference?

code:

import time

N = 100_000_000


class MyClass:
    def __init__(self, value):
        self.value = value

    def direct_read(self):
        tick = time.time()
        for _ in range(N):
            self.value
        tock = time.time()

        print(f"The total time taken for direct read {tock - tick}s")

    def load_read(self):
        var = self.value
        tick = time.time()
        for _ in range(N):
            var
        tock = time.time()

        print(f"The total time taken for load & read {tock - tick}s")


if __name__ == "__main__":
    mc = MyClass(240)
    #   Warm Up the interpreter
    for _ in range(10000000):
        pass
    #   Warm Up the interpreter
    mc.direct_read()
    mc.load_read()

output:

The total time taken for direct read 4.102346181869507s
The total time taken for load & read 3.503936529159546s

self.value needs to first read the local variable self, then get an attribute of that object.

var needs to only read the local variable.

Python doesn’t optimise self in any special way, so accesses to attributes of self will always be slower than access to local variables.

1 Like

You’re actually even hiding much of the difference behind the dominating time of iterating a range. I suggest you use itertools.repeat or use a smaller N and repeat the statement instead, or do both:

        tick = time.time()
        for _ in itertools.repeat(None, N):
            self.value
            self.value
            self.value
            self.value
            self.value
            self.value
            self.value
            self.value
            self.value
            self.value
        tock = time.time()

Attempt This Online!

Also see the table of benchmark results at the end of the “Optimizations” section here and the benchmark script mentioned below it.