setting all elements of a numpy array to zero vs. creating a new array of zeros

I’m doing a bunch of linear algebra on large matrices over and over millions of times in a while loop using numpy, at the beginning of each iteration I need the arrays to be all zeros.

Is it most efficient to reuse the existing arrays by setting all the elements to zero, ie: array[:, :, :] = 0 or to create a new array of all zeros, ie: array = np.zeros((a, b, c))

I would think that setting the elements to zero is best, but I don’t know.

>Solution :

Setting a new array seems 1000 times faster on 10M cells

new array

a = np.zeros((1000,10000))


20.2 µs ± 1.56 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

filling existing array

a[:,:] = 0


19.4 ms ± 1.77 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

Leave a Reply