Created
March 2, 2015 11:58
-
-
Save steinnes/8998d89a86ea8c305b2f to your computer and use it in GitHub Desktop.
dict update vs. assignment speed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK