元组比 Python 中的列表更有效吗? [英] Are tuples more efficient than lists in Python?

查看:28
本文介绍了元组比 Python 中的列表更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

元组和列表在元素的实例化和检索方面是否存在性能差异?

解决方案

dis 模块反汇编函数的字节码,有助于查看元组和列表之间的区别.

在这种情况下,您可以看到访问元素会生成相同的代码,但分配元组比分配列表要快得多.

<预><代码>>>>定义一个():... x=[1,2,3,4,5]... y=x[2]...>>>定义 b():... x=(1,2,3,4,5)... y=x[2]...>>>导入文件>>>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 负载常量 5 (5)15 BUILD_LIST 518 STORE_FAST 0 (x)3 21 LOAD_FAST 0 (x)24 LOAD_CONST 2 (2)27 BINARY_SUBSCR28 STORE_FAST 1 (y)31 LOAD_CONST 0 (无)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_SUBSCR13 STORE_FAST 1 (y)16 LOAD_CONST 0 (无)19 RETURN_VALUE

Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?

解决方案

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.

>>> 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

这篇关于元组比 Python 中的列表更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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