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.

classification
Title: operator.attrgetter is slower than a lambda
Type: performance Stage:
Components: Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: flox, serhiy.storchaka
Priority: low Keywords:

Created on 2013-02-12 16:43 by flox, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (3)
msg181967 - (view) Author: Florent Xicluna (flox) * (Python committer) Date: 2013-02-12 16:43
When two implementations give the same result, I use to run micro benchmarks to give me an hint.

I just noticed that attrgetter is slower than a lambda here:

$ python3.3 -m timeit -s 'from operator import attrgetter; n1 = attrgetter("__name__"); n2 = lambda s: s.__name__' 'rv = n1(int)'
1000000 loops, best of 3: 0.275 usec per loop
$ python3.3 -m timeit -s 'from operator import attrgetter; n1 = attrgetter("__name__"); n2 = lambda s: s.__name__' 'rv = n2(int)'
1000000 loops, best of 3: 0.347 usec per loop

(verified with 2.6, 2.7 and 3.3. But for 2.5 attrgetter is faster)


The function operator.itemgetter does not have same issue.
$ python3.3 -m timeit -s 'from operator import itemgetter; n1 = itemgetter("foot"); n2 = lambda s: s["foot"]; d = {"foot": 42}' 'rv = n1(d)'
10000000 loops, best of 3: 0.122 usec per loop
$ python3.3 -m timeit -s 'from operator import itemgetter; n1 = itemgetter("foot"); n2 = lambda s: s["foot"]; d = {"foot": 42}' 'rv = n2(d)'
10000000 loops, best of 3: 0.176 usec per loop
msg181978 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2013-02-12 22:23
Are you sure? 0.275 < 0.347
msg181979 - (view) Author: Florent Xicluna (flox) * (Python committer) Date: 2013-02-12 22:30
You're right. I've misinterpreted the figures.

Only 2.6 and 2.7 are affected --> closing the issue.
History
Date User Action Args
2022-04-11 14:57:41adminsetgithub: 61396
2013-02-12 22:30:54floxsetstatus: open -> closed
resolution: not a bug
messages: + msg181979
2013-02-12 22:23:30serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg181978
2013-02-12 16:43:38floxsettitle: operator.attrgetter is slow -> operator.attrgetter is slower than a lambda
2013-02-12 16:43:15floxcreate