官方檔案
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is ablock. A script file (a file given as standard input to the interpreter or specified as a command line argument to theinterpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.A code block is executed in an execution frame. A frame contains some administrative information (used for debugging)and determines where and how execution continues after the code block’s execution has completed.
意思是說
Python程式是由代碼塊構造的,塊是一個python程式的文本,他是作為一個單元執行的,代碼塊:一個模塊,一個函式,一個類,一個檔案等都是一個代碼塊,而作為互動方式輸入的每個命令都是一個代碼塊,對于每個def function()都是一個單獨的代碼塊
代碼塊的快取機制
Python在執行同一個代碼塊的初始化物件的命令時,會檢查是否其值經存在,如果存在,會將其重用,換句話說:執行同一個代碼塊時,遇到初始化物件的命令時,他會將初始化的這個變數與值存盤在一個字典中,在遇到新的變數時,會先在字典中查詢記錄,如果有同樣的記錄那么它會重復使用這個字典中的之前的這個值,所以在給出的例子中,檔案執行時(同一個代碼塊)會把i1、i2兩個變數指向同一個物件,滿足快取機制則他們在記憶體中只存在一個,最直接的表現就是:id相同,
代碼塊的快取機制的好處
能夠提高一些字串,整數處理人物在時間和空間上的性能;需要值相同的字串,整數的時候,直接從‘字典’中取出復用,避免頻繁的
創建和銷毀,提升效率,節約記憶體,
小資料池
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in thatrange you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspectthe behaviour of Python in this case is undefined.Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable.Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the stringis created or interned. The distinct values are stored ina string intern pool.
意思是說
Python自動將-5~256的整數進行了快取,當你將這些整數賦值給變數時,并不會重新創建物件,而是使用已經創建好的快取物件,python會將一定規則的字串在字串駐留池中,創建一份,當你將這些字串賦值給變數時,并不會重新創建物件, 而是使用在字串駐留池中創建好的物件,
其實,無論是快取還是字串駐留池,都是python做的一個優化,就是將~5-256的整數,和一定規則的字串,放在一個‘池’(容器,或者字典)中,無論程式中那些變數指向這些范圍內的整數或者字串,那么他直接在這個‘池’中參考,言外之意,就是記憶體中之創建一個,
這樣做的好處是:
能夠提高一些字串,整數處理人物在時間和空間上的性能;需要值相同的字串,整數的時候,直接從‘池’里拿來用,避免頻繁的創建和銷毀,提升效率,節約記憶體,
對于int
小資料池的范圍是-5~256 ,如果多個變數都是指向同一個(在這個范圍內的)數字,他們在記憶體中指向的都是一個記憶體地址,
對于str
1 字串的長度為0或者1,默認都采用了駐留機制(小資料池),
2 字串的長度>1,且只含有大小寫字母,數字,下劃線時,才會默認駐留,
3 用乘法得到的字串:
乘數為1時:僅含大小寫字母,數字,下劃線,默認駐留,含其他字符,長度<=1,默認駐留,含其他字符,長度>1,默認駐留,
乘數>=2時:僅含大小寫字母,數字,下劃線,總長度<=20,默認駐留,
對于bool
無非是Ture / False 無論你創建多少個變數指向True,False,那么他在記憶體中只存在一個, None 更是全域唯一的物件,
可以自由的制定在快取中駐留的資源
from sys import intern
a = intern('monkey@'*100)
b = intern('monkey@'*100)
print(a is b)
指定駐留是你可以指定任意的字串加入到小資料池中,讓其只在記憶體中創建一個物件,多個變數都是指向這一個字串,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/122695.html
標籤:Python
上一篇:Python 記憶體管理和回收
下一篇:Python 模塊和包
