使用连接函数列出vs生成器理解速度

Kev*_*vin 10 python list-comprehension python-2.7

所以我从官方文档中得到了这些例子. https://docs.python.org/2/library/timeit.html

究竟是什么让第一个例子(生成器表达式)比第二个(列表理解)慢?

>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.8187260627746582
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.7288308143615723
Run Code Online (Sandbox Code Playgroud)

Blc*_*ght 18

str.join如果它不是列表或元组,则该方法将其可迭代参数转换为列表.这使得连接逻辑可以多次遍历项目(它会通过一次计算结果字符串的大小,然后是第二次通过以实际复制数据).

你可以在CPython源代码中看到这个:

PyObject *
PyUnicode_Join(PyObject *separator, PyObject *seq)
{
    /* lots of variable declarations at the start of the function omitted */

    fseq = PySequence_Fast(seq, "can only join an iterable");

    /* ... */
}
Run Code Online (Sandbox Code Playgroud)

PySequence_FastC API中的函数正如我所描述的那样.它将任意迭代转换为列表(主要是通过调用list它),除非它已经是列表或元组.

将生成器表达式转换为列表意味着生成器的通常好处(较小的内存占用和可能的短路)不适用str.join,因此生成器的(小)额外开销使其性能更差.


归档时间:

查看次数:

755 次

最近记录:

9 年,9 月 前