Performance Analysis of Python's Dict() and {}
madebyme.today
madebyme.today
$ python -m timeit "list((1, 2, 'a'))"
5000000 loops, best of 5: 53 nsec per loop
$ python -m timeit "[(1, 2, 'a')]"
10000000 loops, best of 5: 30.4 nsec per loop
The first command produces a list of three elements, whereas the second produces a list of one element (being the tuple).To µbench this, you'd want to use `-s` to set up the base object which both snippets then convert.
> python -m timeit -s "t = (1, 2, 'a')" "list(t)"
10000000 loops, best of 5: 39.8 nsec per loop
> python -m timeit -s "t = (1, 2, 'a')" "[*t]"
10000000 loops, best of 5: 25.1 nsec per loop
> python -m timeit -s "[1, 2, 'a']"
50000000 loops, best of 5: 4.28 nsec per loop
(this is 3.11.2 on an M1 Pro)On my machine, the tests that actually do work are:
$ python3 -m timeit -s 't = (1, 2, "a")' 'list(t)'
5000000 loops, best of 5: 44.8 nsec per loop
$ python3 -m timeit -s 't = (1, 2, "a")' '[*t]'
10000000 loops, best of 5: 22.9 nsec per loop
$ python3 -m timeit '[1, 2, "a"]'
10000000 loops, best of 5: 23.1 nsec per loop
...compared to the empty ones: $ python3 -m timeit -s '[1, 2, "a"]'
50000000 loops, best of 5: 5.43 nsec per loop
$ python3 -m timeit ''
50000000 loops, best of 5: 5.8 nsec per loop
(11th gen Intel i7 laptop, Python 3.10.6)All three versions only bench the construction of the list, two of them from a tuple, while the third is a list literal. However if you plug it into `dis` you'll see that it compiles to loading a const tuple and creating a list from that
>>> dis.dis("[1, 2, 'a']")
0 0 RESUME 0
1 2 BUILD_LIST 0
4 LOAD_CONST 0 ((1, 2, 'a'))
6 LIST_EXTEND 1
8 RETURN_VALUE
>>> dis.dis("[*t]")
0 0 RESUME 0
1 2 BUILD_LIST 0
4 LOAD_NAME 0 (t)
6 LIST_EXTEND 1
8 RETURN_VALUEassert type({}) == type(dict())) assert type({1,2,3} == type(set())
Without that, if Python allowed it, would it do given:
a = "xxx"
test_dict = {a=3, b=2}
would it take test_dict to mean {"xxx":3, "b":2} or {"a":3, "b":2} ?JS does the latter always, so the variable a is not related to the literal key a which is understood as an unquoted string "a":
> a = "xxx"
'xxx'
> test_dict = {a:3, b:2}
{ a: 3, b: 2 }
> test_dict["xxx"]
undefined
> test_dict["a"]
3dict(1=5, 6=7, 7="aaa")
dict(hashableInstance="foo", anotherHashableInstance=23, (1,5)=8)
except Python syntax choices of course.
And if they wanted a string, they'd do it like:
dict("1"=5, 6=7, 7="aaa")
However, Python didn't even have sets at all until version 2.3, and they were in a stdlib module instead of being a built-in type until version 2.6. By that time dict notation was well entrenched.
User.objects.get_or_create(
username="bob",
defaults=dict(
email="bob@example.com",
)
this makes it easy to move fields between `defaults` and `kwargs`. Granted, you could achieve the same isomorphism with ** operator, but less readably IMO.For my part, those names are often the same anyway, though, since the calling scope names are often arbitrary and might as well match the parameter names.
{name, age}
does the same in modern JS, assigning the variable to the key with the same name.> x
set()
Well now I know! However I still think the shared usage of curly braces for dicts and sets could be somewhat confusing.
> x = {1, 2, 3}
> x
{1, 2, 3}
(But maybe no one should listen to me because I don't know how to do code blocks on HN.)
{*()}
but I guess it is equivalent to set()
I've noticed this in python in another place f"{var}"
is the same as str(var)
there was some other place I can't recall also noticing that (at least my perception understands that) Python is trying to kill my code golf tendencies.That said, it's probably just my own superstition and of course it doesn't remove my premature optimization tendencies...
Why the triple question marks? You could have just asked the question straight.
If nothing else a search/replace for “dict()” to “{}” could yield an aggregate performance bump with basically zero refactoring cost.
Also re Python in general: love it or hate it, it “won” as the language of ML. If you want to use ML libraries you’ll be in python.
Seriously, though, if every Python program in the world was 0.1% faster, that would probably save a lot of energy.
[1] https://wiki.python.org/moin/PythonSpeed/PerformanceTips
How many minutes / how much energy would it take you to setup a project, run a profiler, do the fix, run tests/CI, commit, release, etc. -vs- how much energy would that 0.1% change save over years?
But I hadn't considered the fact that `dict` can be overridden. That was interesting.
If you're in Python, you should embrace the syntax.
> I'm one of those who prefers words to punctuation -- it's one of the reasons I've picked Python over Perl, for example. "Life is better without braces" (an old Python motto which went on a T-shirt with a cartoon of a smiling teenager;-), after all (originally intended to refer to braces vs indentation for grouping, of course, but, hey, braces are braces!-).
> "Paying" some nanoseconds (for the purpose of using a clear, readable short word instead of braces, brackets and whatnots) is generally affordable (it's mostly the cost of lookups into the built-ins' namespace, a price you pay every time you use a built-in type or function, and you can mildly optimize it back by hoisting some lookups out of loops).
> So, I'm generally the one who likes to write dict() for {}, list(L) in lieu of L[:] as well as list() for [], tuple() for (), and so on -- just a general style preference for pronounceable code. When I work on an existing codebase that uses a different style, or when my teammates in a new project have strong preferences the other way, I can accept that, of course (not without attempting a little evangelizing in the case of the teammates, though;-).
On the other hand list(L) more readable than L[:] because the fact that slicing copies is more obscure, and these are not equivalent when L is not a list.
My take would be to ignore performance and generally do what is more commonly done.
I've run into bugs because i wrote {} for the empty set. Since then i write dict() and set()
It's not punctuation, it's notation. Notation is often essential for readability, we use it for mathematics and music for a very good reason. Consider why JSON is generally preferred to XML. While this guy might have a preference for pointless verbosity, most likely the person who needs to read his code won't.
The performance of pure python code is orders of magnitude worse than non-interpreted languages, there's no point trying to shave off 0.5% off a 5000% difference.
Also Python internals do have some guarantees but in this case it's a semantic guarantee. Because builtins can be shadowed you'll always have to pay the performance cost of looking them up which isn't true for {}.
A 2x speed improvement is very significant if it happens to be in the critical loop of your code. You want a 5000% difference? Just find 6 tweaks like these and you might just get there.
Of course in most cases whatever you're doing to build the dict is more likely taking up most of the time, not building the dict itself, but understanding why one option is 2x as fast is still important. Though one can only hope that it will soon be irrelevant when JITed python becomes a thing.
Optimizations don't compound like this.
I think outside of that niche, though, there are places where people are writing heavily CPU bound code in Python, because it is so easy to become CPU bound. Case in point: I recently sped up an ML ingestion pipeline by multiple thousands of percent by switching from a pure-python PDF library to one that wraps a .so written in C.
So my point, restated: if you're CPU bound in pure Python code and you have time to try and optimize it, just rewrite the critical section in C and use the FFI. This is how 90% of "Python" libraries get implemented anyway. Compared to this, trying to make Python code more CPU efficient is a waste of time.
By the way, I have done work on CPU performance optimizations in Go, Rust and C, and the things you'd typically do are not possible in Python anyway. You're basically left with randomly tweaking the code until the benchmark gives a thumbs up, because it hit on some cpython idiosyncrasy that will completely change around a few versions later.
1) Tweak the code without understanding* of how it'll affect performance, because every single line of code hides behind it such complexity that any improvement you find is almost certainly overfitted to your version of Python. Eventually a benchmark will spit out a nice number. If successful, make a modest improvement, maybe 30%.
2) Rewrite the critical section in C. If you need to optimize further, you are now able to draw on 50 years of know-how in a well-studied field. The improvement will be on the order of thousands of percent.
They both take about the same amount of time. Why should you do (1)?
* There is a difference between random tips like "replace {} with dict()" and fundamentals like how the CPU cache works, or the branch predictor. The former is almost certainly a quirk of the current Python version, the latter has been the same for the past 20-30 years. If you do work on software performance, you rely on your knowledge of the fundamentals and a tool like `perf` to make educated guesses about where you can save some cycles. These fundamentals are basically irrelevant to Python code and so you have to make effectively random attempts.
Changing version or even platform can change the absolute efficiency.
In this case the speed difference will likely always be there, since `dict()` can be overriden (monkey-patched) - hence the interpreter needs to resolve it at runtime.
You could probably override it using Python’s extension system.
Forgive me, I know Python very well, but not C/C++. I’ve learned to make no assumptions.
(My current day job is doing GPU optimization on iterative medical image reconstruction computation. But of course, I don't do that in Python.)
In C/C++, which is faster:
i++;
or
++i;
These days, a decent compiler will output the same machine code, but it wasn't always true, and ++i was faster.
And really, the "dict() vs {}" performance issue can probably get fixed by the interpreter, but it's such a micro-optimization that it's not worth the time and effort.
List comprehensions return a list, and map returns something, while a for loop doesn’t necessarily return anything. I’d expect the overhead of constructing the returned object has an impact on performance.
This is true of every language. You just don't know Python. You probably decided a long time ago that you hate it because of X reason (usually whitespace-as-syntax, as that's probably the most controversial Python design choice), and so refuse to learn anything more and decide you just hate everything.
> Go went as far removing the ternary operator to cut down on this kind of thing.
It surprises me when people get confused by the ternary operator. I never thought it was hard. I wish Python had it. Yes, I know, Python has "a = b if c else d", but that's just weird as it flips the order of expressions around to something that doesn't make much sense.
The ternary is just one example. It's not confusing, it's just indicative of the philosophy of python's design, and it's hardly the worst example.
E: it's actually been 11 years. I'm getting old
IMO, "a = b ? c : d" is much more readable than "a = c if b else d"
In most cases, I love the philosophy of Python's design.
- The global interpreter lock. Multiprocessing is a hacky fix to a problem that most other mainstream languages do not have.
- Performance in general. Python is double digits times or more slower than a lot of other languages at a lot of tasks.
- Weak type system. This is the most glaring issue for large projects. You can add type hints but it's obvious the language wasn't designed with it in mind. You need several layers of linters (mypy, black, etc) to fix this problem, and even then your codebase probably has untyped files. You also won't know if your program is broken until run time.
- Python 3 is not backwards compatible with Python 2. I know why they did this but that doesn't mean this wasn't an expensive problem for a lot of orgs, and 2.7 remains in use in a lot of places and is now a security vulnerability.
- The package management and set up process kind of suck. This is ironic since python is one of the most suggested languages for new devs.
One of advantages python has is that it's easy to use, and that has attracted a lot of development that has lead to a wide variety of libraries including ones that use c and Fortran under the hood like numpy to do things much faster than python. The ease of use also should mean that there's a very large pool of devs to hire from, and that theoretically you're optimizing for lower dev time spent developing. In practice I think the value trade off is worse than people think, especially for larger codebases.
3 to 2 backwards compatibility issues simply weren't possible to prevent. Python had a lot of design mistakes (inadequate differentiation between strings and bytes was one I ran into a lot) that made it impossible to fix without breaking things. Sure, they could have made `print` as a statement still work, but I think it's better that things obviously designed in Python 2 to break.
The weak type system...I dunno I kind of like it. It prevents a lot of the ridiculousness that Java has, where every piece of middleware needs to do type introspection and reflection to get anything done. And it doesn't try to "just make things work" the way JavaScript does and create bizarre rules where {} + {} is NaN and 1 + {} is "1[object Object]". I can certainly see how it can become troublesome on large project.
I think the biggest problem with package management is that `pip` wants to install everything as a system package by default (which requires root), rather than going into a user directory. VirtualEnvs did a lot to fix package management.
I think part of the problem is even comparing Python to Go. They are both "programming languages", but in one of them the expression `x + y` translates to the CPU doing about 2-10 things, and in another the CPU does anywhere between ~1,000 and a few 100,000 things. (I'm ignoring the FFI here.)
It's not like Python does 5,000 things just because it's poorly designed! Actually, I wouldn't want to write math code or do physics simulations in any other language. But conversely, I think if you try to write a backend RPC service in Python, you are just using the wrong tool for the job. Maybe that's because it's what you know and that's fine, but let's not pretend it's a good choice on technical metrics.
In most ways, Python is much closer to bash than it is to Go/Rust/JVM/C. Just like I wouldn't wanna write shell scripts in C, I wouldn't want to write backend code in Python.