Python data structures overhead/performance

有些话、适合烂在心里 提交于 2020-02-04 00:14:33

问题


Is there any performance advantage to using lists over dictionaries over tuples in Python?

If I'm optimising for speed, is there any reason to prefer one over another?


回答1:


Rich,

Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.

That may sound obvious, but picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you.




回答2:


Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.

With that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.




回答3:


The big difference is that tuples are immutable, while lists and dictionaries are mutable data structures. This means that tuples are also faster, so if you have a collection of items that doesn't change, you should prefer them over lists.




回答4:


See the following.

  • Speeding Up Python
  • When should you start optimising code
  • Is premature optimization really the root of all evil?
  • Are tuples more efficient than lists in Python?


来源:https://stackoverflow.com/questions/308912/python-data-structures-overhead-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!