Foreword
In Python, memory pooling technology is often used to improve its performance, so the question is, under what circumstances will pooling? Let us understand through a few examples.
Preliminary knowledge
Before looking at the example, let us first mention a function id() in python, let us look at the function description:
id(obj,/)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.(CPython uses the object \'s memory address.)
Through the above description, we can know that id() will return the unique identifier of the object, and in CPython will return the memory address, that is to say, if the id value of two objects is the same, it can be said that the two objects are the same. .
example
example 00
a =""
b =""print(id(a),id(b))print(a is b)
Output result:
a = “”
b = “”
print(id(a),id(b))
2114853370544 2114853370544
print(a is b)
True
example 01
a ="a"
b ="a"print(id(a),id(b))print(a is b)
Output result:
a = “a”
b = “a”
print(id(a),id(b))
2114883022608 2114883022608
print(a is b)
True
example 02
a ="magic_string"
b ="magic"+"_"+"string"print(id(a),id(b))print(a is b)
Output result:
a = “magic_string”
b = “magic” + “_” + “string”
print(id(a),id(b))
2114887161136 2114887161136
print(a is b)
True
example 03
a ="magic!"
b ="mgaic!"print(id(a),id(b))print(a is b)
Output result:
a = “magic!”
b = “mgaic!”
print(id(a),id(b))
2114885855416 2114889455408
print(a is b)
False
example 04
a,b ="magic!","magic!"print(id(a),id(b))print(a is b)
Output result:
a,b = “magic!”,”magic!”
print(id(a),id(b))
2114885691912 2114885691912
print(a is b)
True
example 05
a ="!"
b ="!"print(id(a),id(b))print(a is b)
Output result:
a = “!”
b = “!”
print(id(a),id(b))
140564571922024 140564571922024
print(a is b)
True
example 06
print(a*20 is 'aaaaaaaaaaaaaaaaaaaa')print(a*21 is 'aaaaaaaaaaaaaaaaaaaaa')
Output result:
print(a20 is ‘aaaaaaaaaaaaaaaaaaaa’)
False
print(a21 is ‘aaaaaaaaaaaaaaaaaaaaa’)
False
to sum up
Through the above 7 examples, it is not difficult for us to have a general understanding of python string pooling. Let's make a brief summary here:
Reference link
The internals of Python string interning
exploring python code objects
Python string interning
Python String objects implementation
The above is the detailed content of the premise of Python string pooling. For more information about Python string pooling, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts