Python “List vs Deque “ performance

Tanin Srivaraphong
Jul 22, 2017 · 1 min read

พอดีมีการเขียนโปรแกรมที่เน้นการใช้ list (array) ซะส่วนใหญ่ แต่ดันไปสะดุดตากับ deque พอดี ก็เลยมา benchmark ตามวิธีใน Stackoverflow ผลก็ได้ออกมาตามนี้

import time
from collections import deque

num = 100000

def append(c):
for i in range(num):
c.append(i)

def appendleft(c):
if isinstance(c, deque):
for i in range(num):
c.appendleft(i)
else:
for i in range(num):
c.insert(0, i)
def pop(c):
for i in range(num):
c.pop()

def popleft(c):
if isinstance(c, deque):
for i in range(num):
c.popleft()
else:
for i in range(num):
c.pop(0)

for container in [deque, list]:
for operation in [append, appendleft, pop, popleft]:
c = container(range(num))
start = time.time()
operation(c)
elapsed = time.time() - start
print "Completed %s/%s in %.2f seconds: %.1f ops/sec" % (container.__name__, operation.__name__, elapsed, num / elapsed)

Result is … (python 2.7.6)

Completed deque/append in 0.01 seconds: 13024170.9 ops/sec
Completed deque/appendleft in 0.01 seconds: 16279076.3 ops/sec
Completed deque/pop in 0.01 seconds: 15642216.8 ops/sec
Completed deque/popleft in 0.01 seconds: 14701381.0 ops/sec
Completed list/append in 0.01 seconds: 14423824.8 ops/sec
Completed list/appendleft in 7.94 seconds: 12601.6 ops/sec
Completed list/pop in 0.01 seconds: 12067161.5 ops/sec
Completed list/popleft in 1.82 seconds: 55073.3 ops/sec

ส่วนรายละเอียดการ implement เชิงลึกให้ไปอ่าน doc ของทาง python เอง ซึ่งใช้ได้ทั้ง python 2 และ python 3 ครับ

deque เหมาะกับงานที่เน้นการใช้งานแนว push/pop เท่านั้น

Tanin Srivaraphong

Written by

Not just a web developer but web engineer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade