Skip to content

Instantly share code, notes, and snippets.

@steinnes
Created March 2, 2015 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steinnes/8998d89a86ea8c305b2f to your computer and use it in GitHub Desktop.
Save steinnes/8998d89a86ea8c305b2f to your computer and use it in GitHub Desktop.
dict update vs. assignment speed
import time
class TimeIt(object):
def __init__(self, name):
self.name = name
def __enter__(self, *args, **kwargs):
self.start_t = time.time()
def __exit__(self, *args, **kwargs):
self.end_t = time.time()
print "{}: took {}s".format(self.name, self.end_t - self.start_t)
d = {}
if __name__ == "__main__":
for n in [1000, 10000, 100000]:
with TimeIt("d.update() x {}".format(n)):
for i in range(n):
d.update({"x": i})
with TimeIt("d[] = x {}".format(n)):
for i in range(n):
d["x"] = i
d.update() x 1000: took 0.000370025634766s
d[] = x 1000: took 0.000133991241455s
d.update() x 10000: took 0.00342798233032s
d[] = x 10000: took 0.00124788284302s
d.update() x 100000: took 0.0354580879211s
d[] = x 100000: took 0.013514995575s
@steinar
Copy link

steinar commented Mar 2, 2015

OK
OK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment