Python数据结构的开销/性能 [英] Python data structures overhead/performance

查看:136
本文介绍了Python数据结构的开销/性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中使用列表而不是字典来取代元组是否有性能优势?

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?

推荐答案

丰富

列表和字典是适合不同需求的野兽.确保不要将列表用于dict散列很完美的线性搜索,因为它的速度要慢一些.另外,如果只需要遍历元素列表,则不要使用字典,因为它比列表占用更多的空间.

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.

这听起来似乎很明显,但是由于更有效的编译代码布局等原因,通过算法选择正确的数据结构具有比微优化更高的性能.如果您在O(n)中的列表中搜索而不是在dict中在O(1)中,微优化不会节省您的时间.

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.

这篇关于Python数据结构的开销/性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆