夸智网
扫描关注夸智网

手机扫描二维码

柚子快报邀请码778899分享:python的小数据池

夸智网2023-09-19博客 5 0A+A-

柚子快报邀请码778899分享:python的小数据池

http://www.51969.com/

一、什么是小数据池?

  小数据池是一种缓存机制,也被称为驻留机制。各种编程语言中都有类似的东西(常量池、小数据池都是指得同一个内容)。

  python自动将-5~256的整数、有一定规则的字符串、都放在一个池中,只要变量是这些范围内的整数或者是字符串,则直接引用,不需要另外开辟一块内存。

  小数据池的应用数据类型:int(-5~256之间的整数)、string(字符串)、bool(布尔值)。其他数据类型不存在驻留机制。

二、小数据池特性

  优点:能够提高字符串、整数的处理速度。省略了创建对象的过程。(节省内存、提高性能和效率)

  缺点:在"池"中创建或者插入新的内容会花费更多的时间。

1、整数

官方文档:

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会被加到小数据池中,每次使用都是同一个对象

在使用的时候,内存中只会创建一个该数据的对象,保存在小数据池中。当使用的时候直接从小数据池中获取对象的内存引用,而不需要重新创建一个新的数据,这样会节省更多的内存区域。

2、字符串

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()函数来指定要驻留的内容。

 

柚子快报邀请码778899分享:python的小数据池

http://www.51969.com/

查看原文

发表评论