python3 bytes 累加使用时的问题

1.先看一下官方定义:

The core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy.

用于操作二进制数据的核心内置类型是字节和字节数组。memoryview支持它们,它使用缓冲区协议访问其他二进制对象的内存,而不需要进行复制。

bytearray objects are a mutable counterpart to bytes objects.

bytearray对象是与bytes对象相对应的可变对象。

2.在tcp通信过程中,接收到数据类型基本上是bytes类型,有时我们可能会对数据多次接收,一次处理,这样就会涉及bytes累加问题。

之前我犯了个错误,直接使用 += 操作,导致程序会出现内存泄漏问题。直接举个栗子:

b1 = bytes()
id1 = id(b1)
b1 += b'tesd0913\x03'
id2 = id(b1)
输出结果为:id1 = 1801125167536
                      id2 = 1801176182000
说明程序已经重新生成了一个新的bytes对象,这是因为bytes为不可变对象。
 
3. 正确的做法如下:
b1 = bytearray()
id1 = id(b1)
b1.extend(b'tesd0913\x03')
b1.extend(b'ddfffh0sdf\d5')
id2 = id(b1)
# 再次转换为bytes
b3 = bytes(b1)
 
此时id1和id2的值都为2810967841328,说明没有新建一个bytearray对象
 
使用bytearray,可以避免多次创建bytes的情况,避免高频率使用情况的程序内存变大
posted @ 2020-04-28 11:13  haozhang13  阅读(1919)  评论(0编辑  收藏  举报