Should I reassign the numpy array?

I have a class and its method. The method is repeated many times at runtime. This method uses an array numpyas a temporary buffer. I do not need to store values ​​inside the buffer between method calls. Should I create an instance member of the array to avoid time leaks when allocating memory during method execution? I know it is preferable to use local variables. But, is it enough for Python to allocate memory for the array only once?

class MyClass:
    def __init__(self, n):
        self.temp = numpy.zeros(n)
    def method(self):
        # do some stuff using self.temp

or

class MyClass:
    def __init__(self, n):
        self.n = n
    def method(self):
        temp = numpy.zeros(self.n)
        # do some stuff using temp

Update: replace empty with zeros

+4
source share
2 answers

, . , , .

:

self.temp = a * b + c

( self.x ):

numpy.multiply(a, b, out=self.x)
numpy.add(c, self.x, out=self.temp)

( ) numexpr einsum .

+1

Numpy , . . , , , python.

, , ( for?), .

, Python , , :)

?

+1

Source: https://habr.com/ru/post/1613121/


All Articles