> [tl;dr] Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
[...]
> ...as a general principle I try to avoid code constructions I know to introduce performance hits.
This is not Pythonic. I appreciate the article and what it showed me, but I do not agree with the conclusion. Do whatever makes your code most readable. Sometimes this may be {}, and sometimes it may be dict(). Most code will not be in a performance-critical path.
While it's nice to get a peek at the implementation details of CPython in this way, I doubt that dict(foo=bar, ...) is typically going to be part of a critical inner loop. It's much more likely to be executed just once before a loop, making this finding irrelevant for real optimization problems.
What are you using Python for? There are plenty of occations where I have made lists of dictionaries, e.g. when I have have large amounts of data that have to be outputted in a certain way, or if it's just logical to store dictionaries instead of instances of some custom class. No performance critical stuff though, and I've almost never used dict(), but still, calling this irrelevant for optimization is a bit harsh...
Doug - thank you for this piece. It clearly took a lot of time to research/write and in addition to providing an interesting insight, provider a great look into disassembling and interpreters.
I would hope that over time insights like this combine with others to create a set of "best practices" across a language. After all, readability is largely tied to convention (multi-line ternary if statements excluded!).
The real benefit of these performance tweaks comes in those people writing libraries. After all, most of the matrix routines we depend on today still tie back to FORTRAN - amazing we are using 40 year old code!
I’ve been reviewing lot of code lately for various open
source and internal projects written in Python. As part of
those reviews, I have noticed what I think is a trend
toward using dict() instead of {} to create dictionaries. I
don’t know exactly why this trend has emerged.
My guess for why this trend has emerged: People prefer javascripts object literal syntax where the attribute names are not quoted.
"Premature optimization is the root of all evil".