Home > Backend Development > Python Tutorial > Difficulties: Which is faster, Python [] or list()? Why fast? How much faster?

Difficulties: Which is faster, Python [] or list()? Why fast? How much faster?

coldplay.xixi
Release: 2020-10-26 18:02:11
forward
1933 people have browsed it

今天python视频教程栏目给大家讲解Python中细微的知识,但是含有巨大能量。

Difficulties: Which is faster, Python [] or list()? Why fast? How much faster?

在日常使用 Python 时,我们经常需要创建一个列表,相信大家都很熟练了吧?

# 方法一:使用成对的方括号语法list_a = []# 方法二:使用内置的 list()list_b = list()复制代码
Copy after login

上面的两种写法,你经常使用哪一个呢?是否思考过它们的区别呢?

让我们开门见山,直接抛出本文的问题吧:两种创建列表的 [] 与 list() 写法,哪一个更快呢,为什么它会更快呢?

注:为了简化问题,我们以创建空列表为例进行分析。关于列表的更多介绍与用法说明,可以查看这篇文章

1、 [] 是 list() 的三倍快

对于第一个问题,使用timeit模块的 timeit() 函数就能简单地测算出来:

>>> import timeit>>> timeit.timeit('[]', number=10**7)>>> timeit.timeit('list()', number=10**7)复制代码
Copy after login

如上图所示,在各自调用一千万次的情况下,[] 创建方式只花费了 0.47 秒,而 list() 创建方式要花费 1.75 秒,所以,后者的耗时是前者的 3.7 倍!

这就回答了刚才的问题:创建空列表时,[] 要比 list() 快不少。

注:timeit() 函数的效率跟运行环境相关,每次执行结果会有微小差异。我在 Python3.8 版本实验了几次,总体上 [] 速度是 list() 的 3 倍多一点。

2、list() 比 [] 执行步骤多

那么,我们继续来分析一下第二个问题:为什么 [] 会更快呢?

这一次我们可以使用dis模块的 dis() 函数,看看两者执行的字节码有何差别:

>>> from dis import dis>>> dis("[]")>>> dis("list()")复制代码
Copy after login

As shown in the figure above, the bytecode of [] has two instructions (BUILD_LIST and RETURN_VALUE), while the bytecode of list() has three instructions (LOAD_NAME, CALL_FUNCTION and RETURN_VALUE).

What do these instructions mean? How to understand them?

First of all, for [], it is a set of literals in Python, which, like literals such as numbers, represent exact fixed values.

In other words, when Python parses it, it knows that it represents a list, so it will directly call the method of building a list in the interpreter (corresponding to BUILD_LIST) to create the list, so it is done in one step.

For list(), "list" is just a common name, not a literal, which means that the interpreter does not recognize it at first.

Therefore, the first step of the interpreter is to find the name (corresponding to LOAD_NAME). It will search in each scope one by one in a certain order (local scope - global scope - built-in scope) until it is found. If it cannot find it, it will throw NameError.

The interpreter sees that "list" is followed by a pair of parentheses, so the second step is to call this name as a callable object, that is, call it as a function (corresponding to CALL_FUNCTION).

Therefore, when list() creates a list, it needs to go through two steps of name search and function calling before it can actually start creating the list (Note: CALL_FUNCTION will also have some function calling processes at the bottom level to get to the bottom of it. BUILD_LIST The same logic, we ignore it here).

At this point, we can answer the previous question: Because list() involves more execution steps, it is slower than [].

3. The speed of list() is improved

After reading the answer process of the first two questions, you may feel that it is not satisfying enough, and you may feel that even if you know this little knowledge, It won't be of much help, and it seems that the weak improvement seems insignificant.

However, the "Why Python" series produced by our Python Cat has always been adhering to the tireless spirit of seeking knowledge, and it is impossible to leave this question unanswered.

Furthermore, because of my habit of divergent thinking, I also thought of another interesting question: Can the speed of list() be improved?

I wrote an article not long ago that just discussed this issue. That is, in the just released Python 3.9.0 version, it implements a faster vectorcall protocol for list(), so The execution speed will be improved to a certain extent.

#Interested students can go to the Python official website to download version 3.9.

According to my multiple rounds of test results, running list() 10 million times in the new version takes about 1 second, which is twice the time it takes to run []. Compared with the previous With nearly 4 times the data, the current version has generally improved a lot.

At this point, we have answered a series of questions. If you find something useful, please like and support! Welcome everyone to pay attention to more exciting content in the future.

Related free learning recommendations: python video tutorial

The above is the detailed content of Difficulties: Which is faster, Python [] or list()? Why fast? How much faster?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template