我正在研究IO python模块。 我有以下两个代码片段:
buffer = b""
buffer += b"Hello World"
buffer += b"Hello World"
buffer += b"Hello World"
import io
with io.BytesIO() as f:
f.write(b"Hello World")
f.write(b"Hello World")
f.write(b"Hello World")
对我来说,这两个 block 几乎做同样的事情。 唯一的区别是第二个可以正常工作,而第一个则不能。
我听说第二种方式通常更快,但我不知道为什么。
有人可以解释一下,相对于第一种方法(在字符串修改中),第二种方法是首选吗?
最佳答案
Bytes objects是不可变的,因此就地添加每次都会创建一个新对象。如果多次重复该操作,则可能会导致性能不佳。来自Python sequence docs (无关部分省略)
- Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:
...
- if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
...
关于python - 何时在 Python 中使用 io.BytesIO() 修改字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119208/