009 Python variable memory management

First, the variable deposit which?

x = 10

Variables stored in memory It was too broad, and we put it specific.

For this large memory computer memory, every definition of a variable will open up in this large memory in a small space, small space and storing the variable value of 10, then this little memory space to a variable name x (house number), x points to 10.

Two, Python garbage collection

For p1.py, if we add a piece of code x = 11, large memory storage space will open up another small variable value 11, the value of the variable x bind another house number, but because of x before, so large memory and will lift x connection 10, so that x and 11. This time because there is no house number 10, so the eyes become garbage python, python will deal with this garbage, release the memory occupied by 10, which is the python garbage collection mechanism. While other languages will need to manually release the memory occupied 10 out.

2.1 reference count

From the above explanation we can know the value of a variable binding as long as the house number, it is not garbage, whereas the value of the variable is not bound to the house number, the value of this variable is garbage, python will automatically clean up the garbage. Here we refer to the count for a given house number professional interpretation in python this house number is called.

x = 10  # 10引用计数加1为1
y = x  # 10引用计数加1为2
x = 11  # 10引用计数减1为1;11引用计数加1为1
del y  # 10引用计数减1为0,触发python垃圾回收机制,python清理10的内存占用

The code is a process of addition and subtraction of the reference count.

Third, small integer pool

In order to avoid creating the same value is repeated application efficiency caused by the memory space, Python interpreter created when the starting pool small integer range [-5,256], small integer within the range of the object is global interpreter is reused within the range, garbage collection will never be recovered.

# 因此当变量值在【-5:256】这个区间内,只要变量值相同,内存地址都一样

When you run the program in pycharm in python, pycharm for reasons of performance, will expand the scope of the pool of small integers, strings, etc. other immutable types are also included a deal will be the same way, we just need to remember this is a live optimization mechanism, as in the end how much range without careful study.

Guess you like

Origin www.cnblogs.com/XuChengNotes/p/11265031.html
009