Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

python - Does setting numpy arrays to None free memory?

I have hundreds of really larges matrices, like (600, 800) or (3, 600, 800) shape'd ones.

Therefore I want to de-allocate the memory used as soon as I don't really need something anymore.

I thought:

some_matrix = None

Should do the job, or is just the reference set to None but somewhere in the Memory the space still allocated? (like preserving the allocated space for some re-initialization of some_matrix in the future)

Additionally: sometimes I am slicing through the matrices, calculated something and put the values into a buffer (a list, because it gets appended all the time). So setting a list to None will definitely free the memory, right?

Or does some kind of unset() method exist where whole identifiers plus its referenced objects are "deleted"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You definitely want to have a look at the garbage collection. Unlike some programming language like C/C++ where the programmer has to free dynamically allocated memory by himself when the space is no longer needed, python has a garbage collection. Meaning that python itself frees the memory when necessary.

When you use some_matrix = None, you unlink the variable from the memory space; the reference counter is decreased, and if it reaches 0, the garbage collector will free the memory. When you use del some_matrix as suggested by MSeifert, the memory is not freed immediately as opposed to what the answer says. According to python doc, this is what happens:

Deletion of a name removes the binding of that name from the local or global namespace

What happened under the hood is that the counter of references to the memory space is reduced by 1 independently of assigning None or using del. When this counter reaches 0, the garbage collector will free the memory space in the future. The only difference is that when using del, it is clear from the context that you do not need the name anymore.

If you look at the doc of the garbage collection, you will see that you can invoke it by yourself or change some of its parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...