我需要在python或numpy中有效地实现固定大小的FIFO。我可能有不同的这样的FIFO,一些用于整数,一些用于字符串等。在这个FIFO中,我需要通过其索引访问每个元素。
对效率的关注是因为这些FIFOS将被用于一个计划的核心,该计划预计将连续运行几天,大量的数据预计将通过它们。因此,该算法不仅需要节省时间,而且还需要节省内存。
现在,在其他语言如C或Java中,我将有效地使用循环缓冲区和字符串指针(字符串FIFOS)来实现这一点。这是python/numpy中的有效方法,还是有更好的解决方案?
具体来说,以下哪种解决方案最有效:
(1)设置了maxlen值的dequeue:(垃圾收集对dequeue的效率有什么影响?)
import collections
l = collections.deque(maxlen=3)
l.append('apple'); l.append('banana'); l.append('carrot'); l.append('kiwi')
print(l, len(l), l[0], l[2])
> deque(['banana', 'carrot', 'kiwi'], maxlen=3) 3 banana kiwi
(2)列出子类解决方案(取自
Python, forcing a list to a fixed size
):
class L(list):
def append(self, item):
list.append(self, item)
if len(self) > 3: self[:1]=[]
l2.append('apple'); l2.append('banana'); l2.append('carrot'); l2.append('kiwi')
print(l2, len(l2), l2[2], l2[0])
> ['banana', 'carrot', 'kiwi'] 3 kiwi banana
(3)一个普通的numpy数组。但这限制了字符串的大小,所以如何为其指定最大字符串大小?
a = np.array(['apples', 'foobar', 'cowboy'])
a[2] = 'bananadgege'
print(a)
> ['apples' 'foobar' 'banana']
# now add logic for manipulating circular buffer indices
(4)上述目标版本,但
python numpy array of arbitrary length strings
说使用对象会撤消numpy的好处
a = np.array(['apples', 'foobar', 'cowboy'], dtype=object)
a[2] = 'bananadgege'
print(a)
> ['apples' 'foobar' 'bananadgege']
# now add logic for manipulating circular buffer indices
(5)或者是否有比上述更有效的解决方案?
顺便说一句,如果有什么帮助的话,我的字符串在长度上有一个最大上限。