【发布时间】:2014-04-01 20:23:24
【问题描述】:
为什么使用切片对列表进行浅拷贝比使用 list 内置函数快得多?
In [1]: x = range(10)
In [2]: timeit x_ = x[:]
10000000 loops, best of 3: 83.2 ns per loop
In [3]: timeit x_ = list(x)
10000000 loops, best of 3: 147 ns per loop
通常当我看到这样奇怪的东西时,它们在 python3 中已修复 - 但这种差异仍然存在:
In [1]: x = list(range(10))
In [2]: timeit x_ = x[:]
10000000 loops, best of 3: 100 ns per loop
In [3]: timeit x_ = list(x)
10000000 loops, best of 3: 178 ns per loop
【问题讨论】:
-
一种解释是
list是一个你需要调用的函数。 -
还有列表需要对每个项目做一些事情,其中一个切片只是将一块内存复制到一个新地址......
-
确实,至少对于
[:]的情况,有可能只在列表中执行memcopy进行优化,而我认为list(x)方法无法执行相同的优化,至少在它完成了许多其他样板文件之前,必须接受许多类型的构造函数必须这样做。这纯粹是猜测,没有深入了解源头。 -
@aruisdante 列表构造函数首先必须检查
PyList_CheckExact,但这只是指针算术和 C 级分支(= 最坏的情况是几十个周期),所以我不认为这将是一个重要因素。
标签: python performance list cpython shallow-copy