English 中文(简体)
为什么要快于斯图尔的名单中?
原标题:Why is tuple faster than list in Python?
最佳回答

所报告的“施工速度”比率仅限constant tuples(其物项按字面表示)。 仔细观察(并重复你的机器——你只是需要把指挥打上空洞/门窗!)

$ python3.1 -mtimeit -s x,y,z=1,2,3   [x,y,z] 
1000000 loops, best of 3: 0.379 usec per loop
$ python3.1 -mtimeit  [1,2,3] 
1000000 loops, best of 3: 0.413 usec per loop

$ python3.1 -mtimeit -s x,y,z=1,2,3   (x,y,z) 
10000000 loops, best of 3: 0.174 usec per loop
$ python3.1 -mtimeit  (1,2,3) 
10000000 loops, best of 3: 0.0602 usec per loop

$ python2.6 -mtimeit -s x,y,z=1,2,3   [x,y,z] 
1000000 loops, best of 3: 0.352 usec per loop
$ python2.6 -mtimeit  [1,2,3] 
1000000 loops, best of 3: 0.358 usec per loop

$ python2.6 -mtimeit -s x,y,z=1,2,3   (x,y,z) 
10000000 loops, best of 3: 0.157 usec per loop
$ python2.6 -mtimeit  (1,2,3) 
10000000 loops, best of 3: 0.0527 usec per loop

我没有做3.0次的测量,因为当然我没有这样做——它已经完全过时,绝对没有任何理由加以保持,因为3.1次优于一切方式(Python 2.7,如果你能够升级,每项任务中的措施几乎比2.6倍快20%——正如你所看到的那样,2.6项速度快于3.1,如果你认真关注业绩,那么2.7项确实是你唯一应当释放的人!)

不管怎么说,这里的关键点是,在每张印章中,从固定字面上打出一个清单,其速度与从变数中点出的数值中推算出来的速度相同,或略微慢;但les子的举动却大不一样——从固定字面上铺一条图通常比从变数中取出的数值上加起来快三倍! 贵方会问,这怎么办?

答复:从固定字面上提取的图可以很容易地由斯珠宝库确定为一种不可改变的固定字面本身:因此,在汇编者将来源变成附形码时,该图基本上只是一成不变的,而相关功能或模块的“用户表”却被封。 当这些密码执行时,他们才需要恢复预设的常识——犹豫不决!

这种轻松的优化不能适用于清单,因为清单是一个可变的物体,因此,如果诸如<代码>[1、2、3]的相同表述(在一份文件上——<代码> 日<>/代码>)执行两次,则该清单至关重要。 模块代表你选择了休息时间;- 每一次都新建了一个新的清单物体—— 施工(如编篡人不能轻视地将其确定为汇编时常备和不可变物体时的修缮工程)只花了一点时间。

That being said, tuple construction (when both constructions actually have to occur) still is about twice as fast as list construction -- and that discrepancy can be explained by the tuple s sheer simplicity, which other answers have mentioned repeatedly. But, that simplicity does not account for a speedup of six times or more, as you observe if you only compare the construction of lists and tuples with simple constant literals as their items!_)

问题回答

Executive Summary

Tuples的表现往往优于在几乎所有类别中的表现:

(1) 可使用constant /61/3/a。

2) 粉碎机可以重新使用,而不是复制。

3) 粉碎机是紧凑的,不会过度分配。

4) 直接参考其要素。

Tuples can be constant folded

恒星的成像可以先由斯普霍素优化器或AST-optimizer进行。 而清单则从零开始:

    >>> from dis import dis

    >>> dis(compile("(10,  abc )",   ,  eval ))
      1           0 LOAD_CONST               2 ((10,  abc ))
                  3 RETURN_VALUE   

    >>> dis(compile("[10,  abc ]",   ,  eval ))
      1           0 LOAD_CONST               0 (10)
                  3 LOAD_CONST               1 ( abc )
                  6 BUILD_LIST               2
                  9 RETURN_VALUE 

Tuples do not need to be copied

滚动式tuple(部分为tuple) 立即返回。 由于les子是不可改变的,因此无需复制:

>>> a = (10, 20, 30)
>>> b = tuple(a)
>>> a is b
True

相比之下,<代码>(一些_list)要求将所有数据抄到新的清单中:

>>> a = [10, 20, 30]
>>> b = list(a)
>>> a is b
False

Tuples do not over-allocate

由于图形尺寸是固定的,因此可以储存起来比需要多分配才能使append(<>append(><>>>/em>业务具有效率的清单要多。

这使冰层具有优势:

>>> import sys
>>> sys.getsizeof(tuple(iter(range(10))))
128
>>> sys.getsizeof(list(iter(range(10))))
200

The comment from Objects/listobject.c, which interpret the what list are do:

/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 * Note: new_allocated won t overflow because the largest possible value
 *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
 */

Tuples refer directly to their elements

物体的参考资料直接输入图标。 相比之下,名单外加一层间接,外加各点。

这为指数化 look和包装提供了微小的速率优势:

$ python3.6 -m timeit -s  a = (10, 20, 30)   a[1] 
10000000 loops, best of 3: 0.0304 usec per loop
$ python3.6 -m timeit -s  a = [10, 20, 30]   a[1] 
10000000 loops, best of 3: 0.0309 usec per loop

$ python3.6 -m timeit -s  a = (10, 20, 30)   x, y, z = a 
10000000 loops, best of 3: 0.0249 usec per loop
$ python3.6 -m timeit -s  a = [10, 20, 30]   x, y, z = a 
10000000 loops, best of 3: 0.0251 usec per loop

https://github.com/python/cpython/blob/master/Include/tupleobject.h” rel=“noreferer”>Here 储存了<代码>(10,20):

    typedef struct {
        Py_ssize_t ob_refcnt;
        struct _typeobject *ob_type;
        Py_ssize_t ob_size;
        PyObject *ob_item[2];     /* store a pointer to 10 and a pointer to 20 */
    } PyTupleObject;

Here:该名单是如何储存的。

    PyObject arr[2];              /* store a pointer to 10 and a pointer to 20 */

    typedef struct {
        Py_ssize_t ob_refcnt;
        struct _typeobject *ob_type;
        Py_ssize_t ob_size;
        PyObject **ob_item = arr; /* store a pointer to the two-pointer array */
        Py_ssize_t allocated;
    } PyListObject;

请注意,图标直接包含两个数据点,而清单标的外围阵的间接层则有两个数据点。

亚历克作出了巨大的回答,但我会试图扩大我认为值得提及的几点内容。 任何绩效差异一般都是很小的,具体实施是具体的:因此,不给农场主。

在CPython,陶器储存在一个单独的记忆库中,因此,在最坏的单一呼吁中,形成一种新的记忆。 清单分两个区:固定区块,所有灰色物体信息,以及数据可变区块。 之所以能够更快地制定教学大纲,这部分原因可能也解释了指数速度的微小差别,因为要紧跟这一点。

CPython也选择了减少记忆分配的办法:在一份免费清单中节省了未分配清单的物体,以便能够再使用,但分配不豁免清单仍需要为数据划拨记忆。 在20个免费名单上为不同规模的拖车节省了图象,因此,分配小图往往不需要任何记忆分配电话。

这种优化在实践中是有用的,但也可能使依赖时间结果的风险太大,当然,如果你转向像“铁Python”这样的内容,即记忆分配工作差别很大的话,这种做法完全不同。

有了<代码> 时间模块,你往往可以解决与业绩有关的问题:

$ python2.6 -mtimeit -s  a = tuple(range(10000))   for i in a: pass 
10000 loops, best of 3: 189 usec per loop
$ python2.6 -mtimeit -s  a = list(range(10000))   for i in a: pass  
10000 loops, best of 3: 191 usec per loop

这表明,学生的体格率比消化人数要快。 我在指数化方面取得了类似结果,但在建筑、图形销毁清单方面:

$ python2.6 -mtimeit  (1, 2, 3, 4)    
10000000 loops, best of 3: 0.0266 usec per loop
$ python2.6 -mtimeit  [1, 2, 3, 4] 
10000000 loops, best of 3: 0.163 usec per loop

因此,如果循环速度或指数化速度是唯一的因素,那么实际上就没有变化,而是建筑,拖车获胜。

In python, we have two types of objects. 1. Mutable, 2. Immutable.
In python, lists come under mutable objects and tuples comes under immutable objects.

  • Tuples are stored in a single block of memory. Tuples are immutable so, It doesn t require extra space to store new objects.

  • Lists are allocated in two blocks: the fixed one with all the Python object information and a variable-sized block for the data.

  • 造成图形的原因比清单要快。

  • It also explains the slight difference in indexing speed is faster than lists, because in tuples for indexing it follows fewer pointers.

Advantages of using tuples:

  • 遗嘱是,在清单使用更多的记忆时,它们使用较少的记忆。

  • We can use tuples in a dictionary as a key but it s not possible with lists.

  • 我们可以查阅标记和清单中的指数。

Disadvantages of tuples:

  • 我们不能在图表中增加一个内容,但我们可以在清单中增加一个内容。

  • We can t sort a tuple but in a list, we can sort by calling list.sort() method.

  • We can t remove an element in tuple but in a list, we can remove an element.

  • 我们可以替代图中的内容,但可以列入清单。


<

在很大程度上,由于图形可变性意味着口译员能够使用更精干的、较快的数据结构,而不是清单。

清单较快的一个领域是从发电机建造的,特别是清单核对表比最接近的对应数字(<代码>tuple(<>>)更快,并有一个发电机的论点:

$ python --version
Python 3.6.0rc2
$ python -m timeit  tuple(x * 2 for x in range(10)) 
1000000 loops, best of 3: 1.34 usec per loop
$ python -m timeit  list(x * 2 for x in range(10)) 
1000000 loops, best of 3: 1.41 usec per loop
$ python -m timeit  [x * 2 for x in range(10)] 
1000000 loops, best of 3: 0.864 usec per loop

尤其请注意,<代码>tuple(generator)似乎是比list(generator)更快的,但[elem for elem in generator]比两者都快得多。

Tuples are identified by python compiler as one immutable constant so compiler created only one entry in hash table and never changed

Lists are mutable objects.So compiler update the entry when we update the list so it is little bit slower compare to tuple





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...