You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Certain methods that heap allocated subtypes inherit suffer a 50-80% performance penalty #78577
The ones I know of are list.__getitem__, dict __contains__ & __getitem__, and (frozen)set.__contains__ but from what I can tell so far it seems like dict.__getitem__ takes the worst hit. For dicts, I've spent a few hours trying to figure out what's getting put into the heap type's mp_subscript slot to slow it down so drastically but I just can't figure it out.
So I just forced dict_subscript into the heap type's mp_subscript slot to confirm the rather obvious impossibility of it breaking anything. Here's a "little" timeit script to demonstrate how horribly inefficient dict.__getitem__ is when called on anything other than an extension type:
assert SlowDictSub.__base__ is dict and FastDictSub.__base__ is dict
assert SlowDictSub.__getitem__ is dict.__getitem__
assert FastDictSub.__getitem__ is dict.__getitem__
mp=dict.fromkeys(range(15))
setup='from __main__ import mp, %s as Dict; d=Dict(mp)'print(f'Comparing execution time of heap allocated dict subtype 'f'versus PyODict_Type (who also inherits dict.__getitem__)...\n')
slown, slowt=timeit.Timer('d[10]', setup%'SlowDictSub').autorange()
print(f'avg. exec {slown/slowt:_.0f} SlowDictSub[x] statements per second')
fastn, fastt=timeit.Timer('d[10]', setup%'FastDictSub').autorange()
print(f'avg. exec {fastn/fastt:_.0f} OrderedDict[x] statements per second')
print()
print(f'SlowDictSub was {1/(fastt/slowt):.2f}x slower than OrderedDict... 'f"Let's see what happens when we fix SlowDictSub's 'broken' ""mp_subscript slot:\n")
slow_tp=cast(id(SlowDictSub), py_type).contentsfast_tp=cast(id(FastDictSub), py_type).contentsslow_tp.tp_as_mapping.contents.mp_subscript= (
fast_tp.tp_as_mapping.contents.mp_subscript)
postn, postt=timeit.Timer('d[10]', setup%'SlowDictSub').autorange()
print(f'avg. exec {postn/postt:_.0f} SlowDictSub[x] after slot change')
print(f'which is now {1/(fastt/postt):.2}x the speed of dict_item')
Comparing execution time of heap allocated dict subtype versus PyODict_Type (who also inherits dict.__getitem__)...
avg. exec 6_220_709 SlowDictSub[x] statements per second
avg. exec 21_894_971 OrderedDict[x] statements per second
SlowDictSub was 3.52x slower than OrderedDict... Let's see what happens when we fix SlowDictSub's 'broken' mp_subscript slot:
avg. exec 21_665_595 SlowDictSub[x] after slot change
which is now 1.0x the speed of dict_item
Well, I found another mystery. Calling tuple.__getitem__ directly, on an actual tuple instance, is 50-80% slower than calling list.__getitem__ even though in theory, they should be virtually identical with maybe tuple access being infinitesimally be faster.
The only difference I found here between the two __getitem__s surprisingly is that tuple *doesn't* have __getitem__ in its method list, while list does.
>>> [].__getitem__
<built-in method __getitem__ of list object at 0x012EE2D8>
>>> ().__getitem__
<method-wrapper '__getitem__' of tuple object at 0x00130030>
Since list is using the wrapper in tp_methods and tuple isn't, it *look* like METH_COEXIST *is* helping but since we know that in both the dict case and now the tuple/list case it is unnecessary, there's clearly a bug somewhere causing multiple arg tuple allocs and or arg parsing. Unfortunately, it takes me several hours to "catch up" from CALL_FUNCTION in ceval.c to something like call_method in typeobject.c and I don't have that kind of time at the moment but hopefully someone notices this again.
Amusingly, this is because of an old hack to make directly calling somedict.__getitem__ fast: 8f5cdaa
But what's the use case of making somedict.__getitem__(x) fast? One should just write somedict[x] instead.
If PEP-580 or PEP-590 is accepted, it should be easy to simply make wrapper descriptors such as somedict.__getitem__ faster, removing the need for METH_COEXIST.
OK, makes sense. Also super() calls I guess: you can write super().__getitem__(x) but not super()[x] (although the latter *could* be implemented if we wanted to).
I see two ways of fixing this:
Make wrapper descriptors faster, removing the need for the METH_COEXIST hack in the first place.
Deal better with METH_COEXIST methods when inheriting.
Since both of these solutions are closely related to the topic of PEP 580/PEP 590, I suggest to try to fix this after either is implemented.
Lib/sets.py benefitted significantly from itertools and METH_COEXIST.
The dunder methods are part of the public API. Serhiy's persona tastes aside, there is no reason not to use them like any other method.
Given a performance trade-off between classes and subclasses, almost universally we give preference to the parent class.
The folks who use itertools with __getitem__ and __contains__ almost always do so because they care about speed and have a preference for a functional style. Removing the current optimization would directly hit those folks and their style of coding, resulting in code that used to be fast and elegant becoming slow.
Marco-Sulla commented on Feb 26, 2020
Marco-Sullamannequin
Mannequin
More actions
I asked why on StackOverflow, and an user seemed to find the reason. The problem for him/her is in update_one_slot().
dict implements directly __contains__() and __getitem__(). Usually, sq_contains and mp_subscript are wrapped to implement __contains__() and __getitem__(), but this way dict is a little faster.
The problem is that update_one_slot() searches for the wrappers. If it does not find them, it does not inherit the __contains__() and __getitem__() of the class, but create a __contains__() and __getitem__() functions that do an MRO search and call the superclass method. This is why __contains__() and __getitem__() of dict subclasses are slower.
Is it possible to modify update_one_slot() so that, if no wrapper is found, the explicit implementation is inherited?
Activity
mr-nfamous commentedon Aug 13, 2018
The ones I know of are list.__getitem__, dict __contains__ & __getitem__, and (frozen)set.__contains__ but from what I can tell so far it seems like dict.__getitem__ takes the worst hit. For dicts, I've spent a few hours trying to figure out what's getting put into the heap type's mp_subscript slot to slow it down so drastically but I just can't figure it out.
So I just forced
dict_subscriptinto the heap type's mp_subscript slot to confirm the rather obvious impossibility of it breaking anything. Here's a "little" timeit script to demonstrate how horribly inefficientdict.__getitem__is when called on anything other than an extension type:Comparing execution time of heap allocated dict subtype versus PyODict_Type (who also inherits dict.__getitem__)...
avg. exec 6_220_709 SlowDictSub[x] statements per second
avg. exec 21_894_971 OrderedDict[x] statements per second
SlowDictSub was 3.52x slower than OrderedDict... Let's see what happens when we fix SlowDictSub's 'broken' mp_subscript slot:
avg. exec 21_665_595 SlowDictSub[x] after slot change
which is now 1.0x the speed of dict_item
benjaminp commentedon Aug 14, 2018
Amusingly, this is because of an old hack to make directly calling somedict.__getitem__ fast: 8f5cdaa
Reverting the dictobject.c changes of the commit, i.e., the following patch, fixes your example.
mr-nfamous commentedon Oct 21, 2018
Well, I found another mystery. Calling tuple.__getitem__ directly, on an actual tuple instance, is 50-80% slower than calling list.__getitem__ even though in theory, they should be virtually identical with maybe tuple access being infinitesimally be faster.
The only difference I found here between the two __getitem__s surprisingly is that tuple *doesn't* have __getitem__ in its method list, while list does.
Since list is using the wrapper in tp_methods and tuple isn't, it *look* like METH_COEXIST *is* helping but since we know that in both the dict case and now the tuple/list case it is unnecessary, there's clearly a bug somewhere causing multiple arg tuple allocs and or arg parsing. Unfortunately, it takes me several hours to "catch up" from CALL_FUNCTION in ceval.c to something like call_method in typeobject.c and I don't have that kind of time at the moment but hopefully someone notices this again.
jdemeyer commentedon Apr 4, 2019
But what's the use case of making somedict.__getitem__(x) fast? One should just write somedict[x] instead.
If PEP-580 or PEP-590 is accepted, it should be easy to simply make wrapper descriptors such as somedict.__getitem__ faster, removing the need for METH_COEXIST.
serhiy-storchaka commentedon Apr 4, 2019
Using them in itertools functions. somedict.__getitem__ is faster that lambda: somedict[x].
As for map() and filter(), comprehensions are almost as fast as map() and filter() with somedict.__getitem__ and are more readable.
jdemeyer commentedon Apr 5, 2019
OK, makes sense. Also super() calls I guess: you can write super().__getitem__(x) but not super()[x] (although the latter *could* be implemented if we wanted to).
I see two ways of fixing this:
Make wrapper descriptors faster, removing the need for the METH_COEXIST hack in the first place.
Deal better with METH_COEXIST methods when inheriting.
Since both of these solutions are closely related to the topic of PEP 580/PEP 590, I suggest to try to fix this after either is implemented.
rhettinger commentedon Jul 19, 2019
Some thoughs:
Lib/sets.py benefitted significantly from itertools and METH_COEXIST.
The dunder methods are part of the public API. Serhiy's persona tastes aside, there is no reason not to use them like any other method.
Given a performance trade-off between classes and subclasses, almost universally we give preference to the parent class.
The folks who use itertools with __getitem__ and __contains__ almost always do so because they care about speed and have a preference for a functional style. Removing the current optimization would directly hit those folks and their style of coding, resulting in code that used to be fast and elegant becoming slow.
Marco-Sulla commentedon Feb 26, 2020
I asked why on StackOverflow, and an user seemed to find the reason. The problem for him/her is in
update_one_slot().dictimplements directly__contains__()and__getitem__(). Usually,sq_containsandmp_subscriptare wrapped to implement__contains__()and__getitem__(), but this waydictis a little faster.The problem is that
update_one_slot()searches for the wrappers. If it does not find them, it does not inherit the__contains__()and__getitem__()of the class, but create a__contains__()and__getitem__()functions that do an MRO search and call the superclass method. This is why__contains__()and__getitem__()ofdictsubclasses are slower.Is it possible to modify
update_one_slot()so that, if no wrapper is found, the explicit implementation is inherited?SO answer: https://stackoverflow.com/a/59914459/1763602