4 ms·
Holy shit, you're right. It's about 33% faster on Python 3.10 on my machine: import operator n1 = operator.itemgetter('name') n2 = lambda x: x['name']
by tonyg 4y ago
Holy shit, you're right. It's about 33% faster on Python 3.10 on my machine:
import operator
n1 = operator.itemgetter('name')
n2 = lambda x: x['name']
x = {'name': 'abcdef'}
import timeit
print(timeit.timeit('n1(x)', globals=globals()))
print(timeit.timeit('n2(x)', globals=globals()))
I'm so surprised because I went and read (what I thought was) the source for operator.itemgetter, which boils down to a wrapper object around the plain version.
It turns out that this is not the source code. As with so many other things in Python, there's a special case you have to know about: there's a separate C implementation of the operator module. :-/
- ssl232 4y ago> It turns out that this is not the source code. As with so many other things in Python, there's a special case you have to know about: there's a separate C implementation of the operator module. :-/ I actually kinda like that Python often maintains 100% compatible pure-Python implementations of various C modules. It's definitely niche, but I have sometimes found myself trying to work out what a module is doing (e.g. with the fancy new PEG parser) and I find it far easier to read Python than C.
- kzrdude 4y agoI'd expect it to be even better improvement inside sort, but maybe my hunch is wrong. The significance is greater there, at least.