Does setting NumPy arrays to None free memory?

Let's understand does setting NumPy arrays to None free memory.
Submitted by Pranit Sharma, on March 06, 2023

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

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?

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 »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.