简体   繁体   中英

how to deallocate heap memory in python

我来自C ++,我曾在堆内存上工作,在那里我不得不使用'new'关键字删除在堆上创建的堆内存,而我一直很困惑在python中为堆内存做什么以阻止内存泄漏,请向我推荐任何有关python内存分配和删除的详细信息。谢谢

You do not have to do anything: Python first of all uses reference counting . This means that for every object it holds a counter that is incremented when you reference that object through a new variable, and decrements the counter in case you let the variable point to something else. In case the counter hits zero, then the object will be deleted (or scheduled for deletion).

This is not enough however, since two objects can reference each other and thus even if no other variable refer to the objects, these objects keep each other alive. For that, Python has an (optional) garbage collector that does cycle detection. In case such cycles are found, the objects are deleted. You can schedule such collection by calling gc.collect() .

In short: Python takes care of memory management itself . Of course it is your task to make sure objects can be released . For instance it is wise not to refer to a large object longer than necessary. You can do this for instance by using the del keyword:

foo = ... # some large object

# ...
# use foo for some tasks

del foo

# ...
# do some other tasks

by using del we have removed the foo variable, and thus we also decremented the counter refering to the object to which foo was refering. As a result, the object foo was refering too can be scheduled for removal (earlier). Of course compilers/interpreters can do liveness analysis, and perhaps find out themselves that you do not use foo anymore, but better be safe than sorry.

So in short: Python manages memory itself by using reference counting and a garbage collector, the thing you have to worry about is that not that much objects are still "alive" if these are no longer necessary .

Python is a high level language. And here you need not worry about memory de-allocation. It is the responsibility of the python runtime to manage memory allocations and de-allocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM