This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

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).
History
Date User Action Args
2015-02-23 12:57:49wbolstersetrecipients: + wbolster, rhettinger, vstinner, serhiy.storchaka, josh.r
2015-02-23 12:57:49wbolstersetmessageid: <1424696269.94.0.574238293502.issue23493@psf.upfronthosting.co.za>
2015-02-23 12:57:49wbolsterlinkissue23493 messages
2015-02-23 12:57:49wbolstercreate