Questions about Python Garbage Collection.

Asked 2 years ago, Updated 2 years ago, 18 views

This is a question related to garbage collection when saving objects as a list.

alist = []
alist.append(SimpleClass())

...

alist = []

After inserting an object into the list as above, if the list is initialized when the use is completed, will the object be garbage collection? (i.e., objects disappear?) or I wonder if I have to delete them explicitly.

python

2022-09-22 18:45

1 Answers

There is no need to initialize.

Python's gc algorithm is simple (a structure promoted by generation according to the number of times referenced, such as Java). Basic reference counting (GC is not operational at this time).If the reference coefficient is 0, it is deleted.) and if it cannot be removed by reference counting, it is typically a case of processing circular reference (using GC at this time). Also, in the case of gc, the problem is fragment processing.

The big and small objects are stacked in the heap, and as you organize and reassign them by gc, you get gaps. If there are more gaps, memory remains when an object larger than the gap is allocated, but memory errors occur because large objects cannot be allocated.

In jvm, there is a compaction process to solve this problem. In other words, the mark and sweep, compacting process is performed. Mark the garbage and sweep it. Then, to eliminate the gap, the objects are rearranged in order through the compacting process. This will eliminate the gap and solve the fragment problem. Of course, when the compaction process is performed, the program is temporarily stopped. Of course...The memory address changes as you move the object, so you cannot do this while you are performing it.

So what about Python? Python has a block pool, which is 8, 16, 24...There are memory blocks in a multiple of 8 in size 512 and if there is a memory request, they are allocated in units of blocks of appropriate size. That is, if it is less than 8 bytes, assign it to one 8-byte block. This means that if you are larger than 8 bytes, you will have a few 32-byte blocks and a few 8-byte blocks for your size to allocate as many blocks as you need. In this case, you can prevent fragmentation because gc will return to the block size when it occurs.

Now the answer is... You don't have to initialize it, but it's organized on its own.


2022-09-22 18:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.