Last active
August 29, 2015 14:06
-
-
Save zzzeek/e768e18d783d7268019e to your computer and use it in GitHub Desktop.
cPython - Which is Faster?
This file contains hidden or 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 timeit | |
| def go1(): | |
| d = {} | |
| for i in range(100): | |
| d[i] = "hi %s" % i | |
| return d | |
| def go2(): | |
| return dict([ | |
| (i, "hi %s" % i) for i in range(100) | |
| ]) | |
| def go3(): | |
| return dict( | |
| (i, "hi %s" % i) for i in range(100) | |
| ) | |
| def go4(): | |
| return { | |
| i: "hi %s" % i for i in range(100) | |
| } | |
| print timeit.timeit("go1()", "from __main__ import go1") | |
| print timeit.timeit("go2()", "from __main__ import go2") | |
| print timeit.timeit("go3()", "from __main__ import go3") | |
| print timeit.timeit("go4()", "from __main__ import go4") |
This file contains hidden or 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 timeit | |
| d = dict((i, "hi %s" % i) for i in range(100)) | |
| def go1(): | |
| d2 = {} | |
| for key in d: | |
| d2[key] = d[key] | |
| return d2 | |
| def go2(): | |
| d2 = {} | |
| for key, value in d.items(): | |
| d2[key] = value | |
| return d2 | |
| print timeit.timeit("go1()", "from __main__ import go1") | |
| print timeit.timeit("go2()", "from __main__ import go2") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment