Click on " Xiaobai Learning Vision " above, and choose to add " star " or " top "
Heavy dry goods, delivered as soon as possible
| Python cat
When using Python on a daily basis, we often need to create a list. I believe everyone is very proficient, right?
# 方法一:使用成对的方括号语法
list_a = []
# 方法二:使用内置的 list()
list_b = list()
Which of the two ways of writing above do you often use? Have you thought about the difference between them?
Let's get straight to the point and throw the question of this article directly: which of the two ways of writing a list, [] and list(), is faster, and why is it faster?
1. [] is three times faster than list()
For the first question, it timeit
can be easily calculated using the module's timeit() function:
>>> import timeit
>>> timeit.timeit('[]', number=10**7)
>>> timeit.timeit('list()', number=10**7)

As shown in the figure above, when each is called 10 million times, the [] creation method only takes 0.47 seconds, while the list() creation method takes 1.75 seconds, so the latter takes 3.7 times the former!
This answers the previous question: [] is much faster than list() when creating an empty list.
Note: The efficiency of the timeit() function is related to the running environment, and the result of each execution will be slightly different. I experimented a few times with Python 3.8, and overall [] is a little more than 3 times faster than list().
2. list() has more execution steps than []
So, let's move on to the second question: why is [] faster?
This time we can use dis
the dis() function of the module to see what is the difference in the bytecode executed by the two:
>>> from dis import dis
>>> dis("[]")
>>> dis("list()")

As shown 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 it?
First, for [], it's a set of literals in Python that, like literals like numbers, represent an exact fixed value.
That is to say, when Python parses it, it knows that it wants to represent a list, so it will directly call the method of building the list in the interpreter (corresponding to BUILD_LIST) to create the list, so it is in one step.
For list(), "list" is just a common name, not a literal, which means that the interpreter doesn't recognize it at first.
Therefore, the first step of the interpreter is to find this 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 finds it, and throws it if it is not found NameError
.
The interpreter sees a pair of parentheses after "list", so the second step is to call the 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 lookup and function call before it can actually start to create a list (Note: CALL_FUNCTION will have some function calling processes at the bottom to reach the same logic as BUILD_LIST. we ignore it).
At this point, we can answer the previous question: list() is slower than [] because it involves more execution steps.
3. The speed of list() is improved
After reading the answering process of the first two questions, you may feel that it is not enough fun, and you may feel that even if you know this cold knowledge, it will not be of much help. It seems that the slight improvement is insignificant.
Moreover, due to the habit of divergent thinking, I also thought of another very interesting question: Can the speed of list() be improved?
I wrote an article not long ago to discuss this issue, that is, in the just released version of Python 3.9.0, 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 as long as the [] running time. Compared with the previous data that is nearly 4 times, The current version is generally improved a lot.
So far, we have answered a series of questions, if you feel that you have gained something, please like and support! Welcome to pay attention to more exciting content in the future.
good news!
Xiaobai learns visual knowledge planet
Start to open to the public 👇👇👇
Download 1: OpenCV-Contrib extension module Chinese version tutorial Reply in the background of the " Xiaobai Learning Vision " public account: Chinese tutorial on extension module , you can download the first Chinese version of the OpenCV extension module tutorial on the whole network, covering extension module installation, SFM algorithm, stereo vision, target tracking, biological vision, super Resolution processing and more than twenty chapters. Download 2: Python Visual Combat Project 52 Lectures Reply in the background of the " Xiaobai Learning Vision " public account: Python visual combat project , you can download including image segmentation, mask detection, lane line detection, vehicle counting, adding eyeliner, license plate recognition, character recognition, emotion detection, text content extraction, Facial recognition and other 31 visual combat projects to help fast school computer vision. Download 3: OpenCV practical project 20 lectures Reply in the background of the "Xiaobai Learning Vision" official account: OpenCV practical project 20 lectures , you can download 20 practical projects based on OpenCV to achieve advanced OpenCV learning. exchange group
Welcome to join the public account reader group to communicate with your peers. There are currently WeChat groups such as SLAM , 3D vision , sensors , autonomous driving, computational photography , detection, segmentation, recognition, medical imaging, GAN , and algorithm competitions (will be gradually subdivided in the future), Please scan the WeChat account below to join the group, note: "nickname + school/company + research direction", for example: "Zhang San + Shanghai Jiaotong University + Visual SLAM". Please remark according to the format, otherwise it will not be approved . After the addition is successful, you will be invited to enter the relevant WeChat group according to the research direction. Please do not send advertisements in the group , otherwise you will be invited out of the group, thank you for your understanding~