Instance variables are bad?
I just found out that using python's instance variables seems to be a very bad idea looking at its performance. Passing local variables is more than 2 times faster. (see my code)
I am writing a ML-Framework and want it to be both fast and memory efficient.
Is there any reason to not use local variables? E. g.
- Are there any differences in memory usage?
- Do you know any structures or cases where instance variables are generally better?
- Are there further problems too be aware of? (E. g. Garbage collector, parallelism, try-blocks, ...)?
And, why is this more than 2x faster anyways? (Especially writing to the variable costs time, other experiment)
Here is the output:
instance: 0.0000125 local: 0.0000051. Speedup: 2.4503532
instance: 1.3528219 local: 0.6189854. Speedup: 2.1855473
of my code:
import time
class WhatsBetter:
def __init__(self, repeats):
a = time.perf_counter()
self.x = 0
self.fun_a(repeats)
b = time.perf_counter()
self.x = 0
self.x = self.fun_b(repeats, self.x)
c = time.perf_counter()
print('instance: {:.7f} \tlocal: {:.7f} \tSpeedup: {:.7f}'.format(b-a, c-b, (b-a)/(c-b)))
def fun_a(self, repeats):
for i in range(1, repeats):
self.x += 1
def fun_b(self, repeats, x):
for i in range(1, repeats):
x += 1
return x
WhatsBetter(100)
WhatsBetter(10000000)