I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there woul
Same question at Performance of accessing class variables in Python - the code here adapted from @Edward Loper
Local Variables are the fastest to access, pretty much tied with Module Variables, followed by Class Variables, followed by Instance Variables.
There are 4 scopes you can access variables from:
The test:
import timeit
setup='''
XGLOBAL= 5
class A:
xclass = 5
def __init__(self):
self.xinstance = 5
def f1(self):
xlocal = 5
x = self.xinstance
def f2(self):
xlocal = 5
x = A.xclass
def f3(self):
xlocal = 5
x = XGLOBAL
def f4(self):
xlocal = 5
x = xlocal
a = A()
'''
print('access via instance variable: %.3f' % timeit.timeit('a.f1()', setup=setup, number=300000000) )
print('access via class variable: %.3f' % timeit.timeit('a.f2()', setup=setup, number=300000000) )
print('access via module variable: %.3f' % timeit.timeit('a.f3()', setup=setup, number=300000000) )
print('access via local variable: %.3f' % timeit.timeit('a.f4()', setup=setup, number=300000000) )
The result:
access via instance variable: 93.456
access via class variable: 82.169
access via module variable: 72.634
access via local variable: 72.199