108 points · by nathiss · 2y ago · 92 comments
$ 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())
dict(1=5, 6=7, 7="aaa")
dict(hashableInstance="foo", anotherHashableInstance=23, (1,5)=8)
except Python syntax choices of course.
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.