Does setting NumPy arrays to None free memory?

Let's understand does setting NumPy arrays to None free memory.
By Pranit Sharma Last updated : December 25, 2023

Problem statement

Suppose that we are working on large numpy arrays. When we work on such large arrays over some time, we need some specific arrays from time to time and we need to de-allocate the memory used as soon as we do not really need something anymore.

The question is should we assign the array or a matrix as None to free the memory or to de-allocate the memory which is used by a particular array?

Setting NumPy arrays to "None", and checking whether it frees up the memory

When you use some_matrix = None, we unlink the variable from the memory space; the reference counter is decreased, and if it reaches 0, the garbage collector will free the memory.

But when you use del some_matrix (which might be thought of by many users), the memory is not freed immediately. Also, especially numpy deletes arrays when the reference counter is zero (or at least it keeps track of the reference counter and lets the OS collect the garbage).

We can understand with help of an example,

Python code to demonstrate - Setting NumPy arrays to "None", frees up the memory or not?

If we create a numpy array:

# Import numpy
import numpy as np

# Creating a array
arr = np.array([1, 2, 3, 4, 5])

# Display Original array
print("Original array:\n",arr,"\n")

Output:

Example: Does setting NumPy arrays to None free memory?

And if we assign none to this array,

# de-allocate the memory
arr = None

It will free the memory "immediately".

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.