作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近开始学习 Python(我小时候使用 GW BASIC 后的第一门编程语言)。我注意到在向 bytes 对象添加字节时,每个字节添加的时间比上一个要长;相比之下,当向列表对象添加整数时,每个整数的添加时间与最后一个整数相同。以下程序说明。
import time
import struct
time.clock() # for Windows
def time_list():
print("adding 9,999,999 0s to one list 9 times:")
a = []
for i in range(9):
start_time = time.clock()
for j in range(9999999):
a += [0]
end_time = time.clock()
print("loop %d took %f seconds" %(i, end_time - start_time))
print()
def time_bytes_object():
print("adding 99,999 pad bytes to a bytes object 9 times:")
a = bytes()
for i in range(9):
start_time = time.clock()
for j in range(99999):
a += struct.pack('<B', 0)
end_time = time.clock()
print("loop %d took %f seconds" %(i, end_time - start_time))
print()
time_list()
time_bytes_object()
最佳答案
Python 中的字节字符串(和 Unicode 字符串)是不可变的,而列表是可变的。
这意味着对字节字符串进行的每个附加( +=
)都必须复制该字符串;原件没有被修改(尽管稍后会被垃圾收集)。相比之下,append
list
的方法(也被 +=
使用)实际上会修改列表。
您要的是bytearray
type,它是一种可变类型,其功能与字节列表非常相似。附加到 bytearray
需要(摊销)常数时间,并且它很容易与字节字符串相互转换。
关于python-3.2 - 对于 Python 3.2 : Why does adding bytes to a bytes object take longer as more bytes are added?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12359190/
我是一名优秀的程序员,十分优秀!