Message236441
Using IPython and CPython 3.4:
>>> d = dict.fromkeys(map(str, range(1000)))
Current implementation:
>>> %timeit sorted(d.items(), key=lambda kv: kv[0])
1000 loops, best of 3: 605 µs per loop
>>> %timeit sorted(d.items(), key=lambda kv: kv[0])
1000 loops, best of 3: 614 µs per loop
Proposed change:
>>> %timeit sorted(d.items(), key=operator.itemgetter(0))
1000 loops, best of 3: 527 µs per loop
>>> %timeit sorted(d.items(), key=operator.itemgetter(0))
1000 loops, best of 3: 523 µs per loop
Alternative without 'key' arg, since all keys in a JSON object must be strings, so the tuples from .items() can be compared directly.:
>>> %timeit sorted(d.items())
1000 loops, best of 3: 755 µs per loop
>>> %timeit sorted(d.items())
1000 loops, best of 3: 756 µs per loop
As you can see, the operator approach seems the fastest on CPython 3.4, even faster than not having a 'key' arg at all (possibly because it avoids doing a tuple compare, which descends into a string compare for the first item). |
|
Date |
User |
Action |
Args |
2015-02-23 12:57:49 | wbolster | set | recipients:
+ wbolster, rhettinger, vstinner, serhiy.storchaka, josh.r |
2015-02-23 12:57:49 | wbolster | set | messageid: <1424696269.94.0.574238293502.issue23493@psf.upfronthosting.co.za> |
2015-02-23 12:57:49 | wbolster | link | issue23493 messages |
2015-02-23 12:57:49 | wbolster | create | |
|