Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Created December 16, 2015 12:55
Show Gist options
  • Save internetimagery/f6bdbc0484e01760f840 to your computer and use it in GitHub Desktop.
Save internetimagery/f6bdbc0484e01760f840 to your computer and use it in GitHub Desktop.
numerical index in dict vs list vs tuple, speed test
import timeit
import random
import sys
def build():
for i in range(1000):
yield (i, random.random())
d = dict(build()) # numerical index
l = list(a[1] for a in build()) # Regular index
t = tuple(a[1] for a in build())
indices = tuple(a for a in range(0, 1000, 20))
def test1():
for i in indices:
var = d[i]
def test2():
for i in indices:
var = l[i]
def test3():
for i in indices:
var = t[i]
print "Dict", sys.getsizeof(d)
print "List", sys.getsizeof(l)
print "Tuple", sys.getsizeof(t)
# Dict 24716
# List 4276
# Tuple 4028
print "Dict", timeit.timeit(test1)
print "List", timeit.timeit(test2)
print "Tuple", timeit.timeit(test3)
# Dict 2.79323147866
# List 1.791129993
# Tuple 2.44775280693
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment