Fall in love with the python series-python performance (6): performance optimization of new list objects

The list in Cpython is actually implemented by a variable-length array

New lists often use this kind of writing:

[i for i in range(N)]

Such wording is not only cool, simple, write this method can actually speed it

An experiment was done below:

import time
import numpy as np

st=time.time()
evens = []
for i in range(1<<26):
    if i % 2 == 0:
        evens.append(i)
print(time.time()-st)

st=time.time()
[i for i in range(1<<26) if i % 2 == 0]
print(time.time()-st)

operation result:

5.2301719188690186
2.8356707096099854

The speed increase has almost doubled, and the readability is also more concise

Guess you like

Origin blog.csdn.net/zhou_438/article/details/109246937