Sha*_*kan 4 python performance generator
我有一个近2k字典的列表.而且我多次使用该列表.例如:
c = myClass()
c.create(source) # where source is a text of approximately 50k chars
# this method creates the list that has approximately 2k dictionaries
item = c.get(15012) # now, this one loops thru the list to find an item
# whenever the condition is matched, the for loop is broken and the value is returned
item2 = c.prevItem(item) # this one also loops thru the list by reversing it and bringing the next item
Run Code Online (Sandbox Code Playgroud)
现在,想象一下这个场景我一遍又一遍地使用相同的列表.由于列表很大,我想使用生成器,但据我所知,生成器必须在抛出StopIteration时重新创建.所以基本上,在这种情况下,使用发电机是否方便?还是在速度方面有更有效的方法?
听起来像你必须决定你宁愿做什么:
1)保存值,这样您就不必重新计算它们,但是需要更多的空间来重新计算它们.
2)每次重新计算它们,但节省空间,因为你不必存储它们.
如果你考虑一下,无论你使用什么样的发生器/列表/任何东西,这两件事中的一件必须发生.而且我认为没有一个简单的硬规则可以说哪个更好.(就个人而言,我会选择一个,不要回头.你的一生都在你面前.)