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/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 it might look like a bad idea to instantiate StressTestMember
and StressTestLocal
on each iterations but it makes sense in the modeled program where these are basically Active Records.
After a simple benchmark,
- LOCAL access test: 0m22.836
- MEMBER access test: 0m32.648s
The local version is ~33% faster while still part of a class. Why?
m = self.m
? It wouldn't make any difference in this test, but my version ofdo_work()
is a loop that runs millions of times. – Lythraceous