Detailed explanation of the use of small and medium integer object pool and large integer object pool in Python

  • 2021-07-13 05:29:41
  • OfStack

1. Small integer object pool

Integers are widely used in programs. In order to optimize the speed, Python uses a small integer object pool to avoid frequent application and destruction of memory space for integers.

Python defines small integers as [-5,256] These integer objects are pre-established and will not be garbage collected. In an Python program, no matter where this integer is in LEGB,

All integers in this range use the same object. Similarly, the same is true of a single letter.


In [1]: a=-5

In [2]: b=-5

In [3]: a is b
Out[3]: True

In [4]: a=256

In [5]: b=256

In [6]: a is b
Out[6]: True

In [7]: a=1000

In [8]: b=1000

In [9]: a is b
Out[9]: False
intern Mechanism handles spaces 1 There is a great chance to reuse 10 words, so create 1 A space is created multiple times, but the string length is greater than 20 Is not to create 1 Twice. 
In [13]: a="abc"

In [14]: b="abc"

In [15]: a is b
Out[15]: True

In [16]: a="helloworld"

In [17]: b="helloworld"

In [18]: a is b
Out[18]: True

In [19]: a="hello world"

In [20]: b="hello world"

In [21]: a is b
Out[21]: False
 

s1 = "abcd"
s2 = "abcd"
print(s1 is s2)

s1 = "a" * 20
s2 = "a" * 20
print(s1 is s2)

s1 = "a" * 21
s2 = "a" * 21
print(s1 is s2)

s1 = "ab" * 10
s2 = "ab" * 10
print(s1 is s2)

s1 = "ab" * 11
s2 = "ab" * 11
print(s1 is s2)
# True
# True
# False
# True
# False

2. Large integer object pool. Terminals are executed once every time, so every large integer is re-created, and in pycharm, every run is all the code loaded in memory, belonging to a whole, so

At this point, there will be a large integer object pool, that is, the large integers in one code block are the same object. c1 and d1 are in one code block, while c1.b and c2.b have their own code blocks, so they are not equal.


C1.b is C2.b
In [22]: a=1000

In [23]: b=1000

In [24]: a is b
Out[24]: False

In [25]: a=-1888

In [26]: b=-1888

In [27]: a is b
Out[27]: False

In [28]: 
c1 = 1000
d1 = 1000
print(c1 is d1) # True

class C1(object):
  a = 100
  b = 100
  c = 1000
  d = 1000


class C2(object):
  a = 100
  b = 1000


print(C1.a is C1.b) # True
print(C1.a is C2.a) # True
print(C1.c is C1.d) # True
print(C1.b is C2.b) # False

Related articles: