[Python-ideas] namedtuple with ordereddict
Tim Peters
tim.peters at gmail.com
Wed Jul 19 11:20:38 EDT 2017
[Giampaolo Rodola' <g.rodola at gmail.com>]
> Still much slower (-4.3x) than plain tuples though:
>
> $ python3.7 -m timeit -s "import collections; Point => collections.namedtuple('Point', ('x', 'y'));" "Point(5, 11)"
> 1000000 loops, best of 5: 313 nsec per loop
>
> $ python3.7 -m timeit "tuple((5, 11))"
> 5000000 loops, best of 5: 71.4 nsec per loop
I believe this was pointed out earlier: in the second case,
1. (5, 11) is built at _compile_ time, so at runtime it's only
measuring a LOAD_FAST to fetch it from the code's constants block.
2. The tuple() constructor does close to nothing when passed a tuple:
it just increments the argument's reference count and returns it.
>>> t = (1, 2)
>>> tuple(t) is t
True
In other words, the second case isn't measuring tuple _creation_ time
in any sense: it's just measuring how long it takes to look up the
name "tuple" and increment the refcount on a tuple that was created at
compile time.
More information about the Python-ideas
mailing list