Python cho phép khởi tạo list nhiều cách, nhưng hiệu năng khác nhau. Vòng lặp for chậm, map(), filter() nhanh hơn vì viết bằng C.
So sánh 4 phương pháp (10000 phần tử, lặp 500 lần)
import time
forLoopTime = []
whileLoopTime = []
listCompTime = []
starOpTime = []
for _ in range(500):
# for loop
start = time.time()
a = []
for i in range(10000):
a.append(0)
forLoopTime.append(time.time() - start)
# while loop
start = time.time()
a = []
i = 0
while i < 10000:
a.append(0)
i += 1
whileLoopTime.append(time.time() - start)
# list comprehension
start = time.time()
a = [0 for i in range(10000)]
listCompTime.append(time.time() - start)
# * operator
start = time.time()
a = [0] * 10000
starOpTime.append(time.time() - start)
print(f"for loop: {sum(forLoopTime)/500:.6f}s")
print(f"while loop: {sum(whileLoopTime)/500:.6f}s")
print(f"list comp: {sum(listCompTime)/500:.6f}s")
print(f"* operator: {sum(starOpTime)/500:.6f}s")Kết quả tiêu biểu
for loop: 0.006237s while loop: 0.008877s list comp: 0.003185s * operator: 0.000372s
Kết luận
- Nhanh nhất:
[0] * n(toán tử *). - Tiếp theo: list comprehension.
- Chậm nhất: while loop, sau đó for loop.
- Lưu ý:
[[]] * ntạo n tham chiếu đến cùng một list con → dùng list comprehension cho list lồng nhau.