The Performance Impact of Using dict() Instead of {} in CPython 2.7
doughellmann.com
doughellmann.com
> [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."Premature optimization is the root of all evil".
{k: v for k, v in some_iterable}
I'd never seen that. Nice. :)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!
Thanks again.
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.After writing javascript:
var o = { a: 1, b: 2};
... it feels a bit clunky to write Python:
o = { "a": 1, "b": 2}
It does the same thing with [] and list().
I'd rather just use what feels right at the time thanks, PyCharm.
It's under, "introspections" if anyone else is looking.