Message236441
| Author |
wbolster |
| Recipients |
josh.r, rhettinger, serhiy.storchaka, vstinner, wbolster |
| Date |
2015年02月23日.12:57:49 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1424696269.94.0.574238293502.issue23493@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
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). |
|