When trying to solve a more complicated problem, I came to compare access speed with vs member local variables.
Here's the test program:
#!/usr/bin/env python MAX=40000000 class StressTestMember(object): def __init__(self): self.m = 0 def do_work(self): self.m += 1 self.m *= 2 class StressTestLocal(object): def __init__(self): pass def do_work(self): m = 0 m += 1 m *= 2 # LOCAL access test for i in range(MAX): StressTestLocal().do_work() # MEMBER access test for i in range(MAX): StressTestMember().do_work()
I know that it might seem like a bad idea to instantiate StressTestMember and StressTestLocal at each iteration, but that makes sense in a simulated program where they are mostly active records.
After a simple test
- Local Access Test: 0m22.836
- MEMBER Access Check: 0m32.648s
The local version is ~ 33% faster, although part of the class. Why?
performance python benchmarking
yadutaf
source share