$ python -m perf timeit --rigorous --duplicate 10 --hist --stats -s 'import collections; Point = collections.namedtuple("Point", "x y")' 'Point(10.5, 11.5)'
$ python -m perf timeit --rigorous --duplicate 10 --hist --stats '{"x": 10.5, "y": 11}'
Point(10.5, 11.5)
is 6 times slower than {'x': 10.5, 'y':11.5}
.
The absolute times are 635 ns +- 26 ns
vs. 105 ns +- 4 ns
. Don't
create classes at the function level unless you know why you need
it. If your API requires dict
than use dict
-- it has nothing to
do with performance.
This microbenchmark tells only half of the story at best. It only creates the structures but does not access the elements.
First of all, if possible, it needs to be determined if the program is
If the program is write heavy, then indeed the non-keyword version of
dict
is faster:namedtuple
is not designed for updating, and its_replace()
returns a new instance, so no point in benchmarking that, it will be very slow and left as an exercise for the reader.Howevery if the program is read heavy,
namedtuple
does not seem significantly slower even when using the dot notation lookup, the style that makes the code much much more readable:For number crunching probably none of these are the fastest. For all the rest readability beats a miniscule speedup, especially if the initial values never change.