Repository navigation
Optimize copy() for SortedList, SortedKeyList, SortedDict and 2-sublist indexing - #269
Conversation
…ast-path 2-sublist indexing - SortedList.copy: copy existing sublists and maxes directly instead of re-iterating and running Timsort over all N elements. - SortedKeyList.copy: copy pre-extracted keys and sublists directly, avoiding running the key-function N times and re-sorting (up to 20x faster with non-trivial keys). - SortedDict.copy: copy underlying dict with dict.update and use the optimized self._list.copy() instead of re-extracting items() and sorting keys from scratch. - _pos & _loc: add O(1) fast path for len(_lists) == 2, bypassing _build_index() and binary tree traversal.
|
The fast copy path skips subclass initialization, so a copy can have the right type but be unusable. For example, a default-factory from copy import copy
from sortedcontainers import SortedDict
class DefaultSortedDict(SortedDict):
def __init__(self, *args, **kwargs):
self.default_factory = list
super().__init__(*args, **kwargs)
def __missing__(self, key):
value = self.default_factory()
self[key] = value
return value
original = DefaultSortedDict({'a': [1]})
original.copy()['b'] # base: []; PR head: AttributeError
copy(original)['b'] # same failureOn Keeping the fast path for the exact built-in container classes and using the previous constructor path for subclasses preserves this behavior. I checked that fallback on Python 3.10 and 3.14, including empty/nonempty containers and both copy entry points. |
|
Thanks for catching that, @manav4u! You're right — bypassing I've updated All 292/292 coverage tests pass locally ( |
Summary
This PR optimizes shallow copying across SortedList, SortedKeyList, and SortedDict, and adds a fast-path for 2-sublist indexing in _pos and _loc:
SortedList.copy:
SortedKeyList.copy:
SortedDict.copy:
SortedList._pos & SortedList._loc:
Benchmarks
Microbenchmarks (50 iterations)
Verification