python的小數據池

1、什麼是小數據池?

  小數據池是一種緩存機制,也被稱爲駐留機制。各類編程語言中都有相似的東西(常量池、小數據池都是指得同一個內容)。python

  python自動將-5~256的整數、有必定規則的字符串、都放在一個池中,只要變量是這些範圍內的整數或者是字符串,則直接引用,不須要另外開闢一塊內存。編程

  小數據池的應用數據類型:int(-5~256之間的整數)、string(字符串)、bool(布爾值)。其餘數據類型不存在駐留機制。緩存

2、小數據池特性

  優勢:可以提升字符串、整數的處理速度。省略了建立對象的過程。(節省內存、提升性能和效率)編程語言

  缺點:在"池"中建立或者插入新的內容會花費更多的時間函數

一、整數

官方文檔:
    The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you 
actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python in 
this case is undefined.
  • 在python中,-5~256會被加到小數據池中,每次使用都是同一個對象
  • 在使用的時候,內存中只會建立一個該數據的對象,保存在小數據池中。當使用的時候直接從小數據池中獲取對象的內存引用,而不須要從新建立一個新的數據,這樣會節省更多的內存區域。

二、字符串

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 string is created or interned. The distinct values are
 stored ina string intern pool. –引⾃自維基百科
  • 若是字符串的長度是0或者1,都會默認進行緩存。(中文字符無效)
  • 字符串長度大於1,可是字符串中只包含數字,字母,下劃線時會被緩存。
  • 用乘法獲得的字符串:1)乘數爲1,僅包含數字,字母,下劃線時會被緩存。若是包含其餘字符,而長度<= 1也會被駐存(中文字符除外)。2)乘數大於1,僅包含數字,字母,下劃線時會被緩存,但字符串長度不能大於20
  • 指定駐留:能夠經過sys模塊中的intern()函數來指定要駐留的內容。
相關文章
相關標籤/搜索