Are tuples more efficient than lists in Python?
在stackoverflow上看到的一篇,刚好解答了我的疑惑:http://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python
The "dis" module disassembles the byte code for a function and is useful to see the difference between tuples and lists.
In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | >>> def a(): ... x = [ 1 , 2 , 3 , 4 , 5 ] ... y = x[ 2 ] ... >>> def b(): ... x = ( 1 , 2 , 3 , 4 , 5 ) ... y = x[ 2 ] ... >>> import dis >>> dis.dis(a) 2 0 LOAD_CONST 1 ( 1 ) 3 LOAD_CONST 2 ( 2 ) 6 LOAD_CONST 3 ( 3 ) 9 LOAD_CONST 4 ( 4 ) 12 LOAD_CONST 5 ( 5 ) 15 BUILD_LIST 5 18 STORE_FAST 0 (x) 3 21 LOAD_FAST 0 (x) 24 LOAD_CONST 2 ( 2 ) 27 BINARY_SUBSCR 28 STORE_FAST 1 (y) 31 LOAD_CONST 0 ( None ) 34 RETURN_VALUE >>> dis.dis(b) 2 0 LOAD_CONST 6 (( 1 , 2 , 3 , 4 , 5 )) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 ( 2 ) 12 BINARY_SUBSCR 13 STORE_FAST 1 (y) 16 LOAD_CONST 0 ( None ) 19 RETURN_VALUE |
In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil").
Python makes this very easy: timeit is your friend.
1 2 3 4 5 | $ python -m timeit "x=(1,2,3,4,5,6,7,8)" 10000000 loops, best of 3: 0.0388 usec per loop $ python -m timeit "x=[1,2,3,4,5,6,7,8]" 1000000 loops, best of 3: 0.363 usec per loop |
and...
1 2 3 4 5 | $ python -m timeit -s "x=(1,2,3,4,5,6,7,8)" "y=x[3]" 10000000 loops, best of 3: 0.0938 usec per loop $ python -m timeit -s "x=[1,2,3,4,5,6,7,8]" "y=x[3]" 10000000 loops, best of 3: 0.0649 usec per loop |
So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.
Of course if you want to change an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable).
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2010-12-24 幻方常规解法汇总