gpt4 book ai didi

python - 这对缓冲区操作更有效 : python strings or array()

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:52 25 4
gpt4 key购买 nike

我正在构建一个用于取证目的的处理磁盘缓冲区的例程。我最好使用 python 字符串还是 array() 类型?我的第一个想法是使用字符串,但我试图避免 unicode 问题,所以也许 array('c') 更好?

最佳答案

使用最自然的(字符串)编写代码,找出它是否太慢然后改进它。

在大多数情况下,数组可以用作 str 的直接替代品,只要您限制自己对索引和切片访问。两者都是定长的。两者应该具有大致相同的内存要求。数组是可变的,以防您需要更改缓冲区。数组可以直接从文件中读取,因此读取时不会有速度损失。

不过,我不明白您如何通过使用数组来避免 Unicode 问题。 str 只是一个字节数组,对字符串的编码一无所知。

我假设您提到的“磁盘缓冲区”可能相当大,因此您可能会考虑使用 mmap :

Memory-mapped file objects behave like both strings and like file objects. Unlike normal string objects, however, these are mutable. You can use mmap objects in most places where strings are expected; for example, you can use the re module to search through a memory-mapped file. Since they’re mutable, you can change a single character by doing obj[index] = 'a', or change a substring by assigning to a slice: obj[i1:i2] = '...'. You can also read and write data starting at the current file position, and seek() through the file to different positions.

关于python - 这对缓冲区操作更有效 : python strings or array(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2200027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com