Execution time of built-in data structures | Calling the function vs literal syntax
I ran some timeit's on my old machine (a 2011 mbp) a while ago, comparing calling the built-in functions vs empty literals.
I recently got an M1 mbp from my employer, so I thought I would run some tests on the new system and compare the results.
Last time I didn't run every built-in data structure on my 2011 machine, I only ran list & dict, however I still think it's an interesting exercise.
This time around I tested list, dict, tuple & set on my new M1 machine.
Results on my 2011 mbp:
list:
$ python -m timeit '[]'
5000000 loops, best of 5: 44.2 nsec per loop
$ python -m timeit 'list()'
2000000 loops, best of 5: 126 nsec per loop
dict:
$ python -m timeit '{}'
5000000 loops, best of 5: 44.9 nsec per loop
$ python -m timeit 'dict()'
2000000 loops, best of 5: 166 nsec per loop
Results on the M1 mbp:
list:
❯ python -m timeit '[]'
20000000 loops, best of 5: 12.5 nsec per loop
❯ python -m timeit 'list()'
10000000 loops, best of 5: 39 nsec per loop
dict:
❯ python -m timeit '{}'
20000000 loops, best of 5: 12.1 nsec per loop
❯ python -m timeit 'dict()'
5000000 loops, best of 5: 52.1 nsec per loop
tuple:
❯ python -m timeit '()'
50000000 loops, best of 5: 6.92 nsec per loop
❯ python -m timeit 'tuple()'
10000000 loops, best of 5: 24.4 nsec per loop
set:
❯ python -m timeit '{*()}'
10000000 loops, best of 5: 39.5 nsec per loop
❯ python -m timeit 'set()'
5000000 loops, best of 5: 42.9 nsec per loop
The results are quite interesting.
Disregarding the minute scale we're operating on here, there is quite a big difference between calling functions and using literal syntax.
Maybe some of you have some data from your own machines you can post? I'd be interested in more data points, perhaps even cross-platform.
4 comments · 76% upvoted · other discussions
It's well known behavior, that calling list() or dict() is slower than calling [] Or {} respectively. It's because the interpreter needs to resolve the function names first. So it adds an extra step. You can use the dis module to get the bytecode for the different examples, if you want to learn more about it.
OoTMM [OP] 1 points · Sep 2021
I know it's well known behaviour, my intent was not to suggest it wasn't. The extra step is there because the global scope might've been rebound to something else.
However, I was interested in the results themselves, since it's quite a big difference, and the scale over time is interesting (imo).
I originally tested my old machine in a thread here, discussing this article: https://deepsource.io/blog/8-new-python-antipatterns/
I thought the advancements and any other possible data points would be fun to discuss and compare.