0

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)
ducktalez
  • 115
  • 1
  • 6
  • 2
    [Possible explanation of this](https://stackoverflow.com/questions/12397984/why-is-local-variable-access-faster-than-class-member-access-in-python) – DarrylG Dec 26 '19 at 21:19
  • 1
    Note you can use `__slots__` to improve the performance of attribute access. Instance variables **are not bad**. But if you are writing code that is for an ML framework that is performance critical, you should probably shouldn't be using *python at all* and instead using C/C++. At the very least, you should be writing the performance critical things using `numpy`/`scipy`, where linear algebra routines are utilizing BLAS/LAPACK backends written in C/Fortran. – juanpa.arrivillaga Dec 26 '19 at 21:25
  • Thank you for your comments! I think the explaination seems correct, to much memory access. I think __slots__ or pypy seems pretty cool aswell. :) – ducktalez Dec 27 '19 at 00:29

0 Answers0