为什么使用slice [:]复制列表比使用明显的方法快? [英] Why is copying a list using a slice[:] faster than using the obvious way?

查看:107
本文介绍了为什么使用slice [:]复制列表比使用明显的方法快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用切片浅复制列表比使用内置的list快得多?

Why is shallow-copying a list using a slice so much faster than using list builtin?

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中修复-但这种差异仍然存在:

Usually when I see weird things like this, they're fixed in python3 - but this discrepancy is still there:

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

推荐答案

区别在于附加函数调用(仅SLICE+0CALL_FUNCTION 1以及额外的堆栈操作):

The difference is in additional function call (just SLICE+0 vs CALL_FUNCTION 1 with extra stack operations):

>>> import dis
>>> def f(lst):
...  return lst[:]
... 
>>> def f1(lst):
...  return list(lst)
... 
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (lst)
              3 SLICE+0             
              4 RETURN_VALUE        
>>> dis.dis(f1)
  2           0 LOAD_GLOBAL              0 (list)
              3 LOAD_FAST                0 (lst)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE 

来自 dis docs :

SLICE + 0()
实现TOS = TOS [:].

SLICE+0()
Implements TOS = TOS[:].

(TOS-堆栈顶部)

CALL_FUNCTION(argc)
调用一个函数. argc的低字节指示 位置参数的数量,高字节的数量 关键字参数.在堆栈上,操作码找到关键字 参数优先.对于每个关键字参数,该值位于 钥匙.在关键字参数下方,位置参数为 在堆栈上,最右边的参数在顶部.以下 参数,要调用的函数对象在堆栈上.弹出全部 函数参数,以及函数本身脱离堆栈,并推送 返回值.

CALL_FUNCTION(argc)
Calls a function. The low byte of argc indicates the number of positional parameters, the high byte the number of keyword parameters. On the stack, the opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, the function object to call is on the stack. Pops all function arguments, and the function itself off the stack, and pushes the return value.

这篇关于为什么使用slice [:]复制列表比使用明显的方法快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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