Skip to content

Optimize copy() for SortedList, SortedKeyList, SortedDict and 2-sublist indexing - #269

Open
millisdoe-glitch wants to merge 2 commits into
grantjenks:masterfrom
millisdoe-glitch:perf/optimize-copy-and-two-sublist-indexing
Open

millisdoe-glitch wants to merge 2 commits into
grantjenks:masterfrom
millisdoe-glitch:perf/optimize-copy-and-two-sublist-indexing

Conversation

@millisdoe-glitch

Copy link
Copy Markdown

Summary

This PR optimizes shallow copying across SortedList, SortedKeyList, and SortedDict, and adds a fast-path for 2-sublist indexing in _pos and _loc:

  1. SortedList.copy:

    • Previously called self.class(self), which iterated through the list, re-allocated a flat list of $ items, ran Python's sorted() (Timsort), and re-chunked into sublists.
    • Now directly copies the already-partitioned sublists ([sublist.copy() for sublist in self._lists]) and _maxes.
    • Eliminates (N \log N)$ sorting and peak memory overhead.
  2. SortedKeyList.copy:

    • Previously called self.class(self, key=self._key), which re-evaluated the user's key function on all $ elements and re-sorted.
    • Now copies self._lists and self._keys directly without calling the key function at all.
    • For lists with a non-trivial key function, this yields a ~20x speedup.
  3. SortedDict.copy:

    • Previously called self.class(self._key, self.items()), iterating all item tuples and building/sorting keys from scratch.
    • Now copies dictionary entries via fast C-level dictionary update and leverages the optimized self._list.copy().
  4. SortedList._pos & SortedList._loc:

    • For lists with len(self._lists) == 2 (very common for lists up to 2,000 items with default load factor), idx in the second sublist is trivially idx - len(self._lists[0]).
    • This directly returns without invoking _build_index() or traversing the binary index tree.

Benchmarks

Microbenchmarks (50 iterations)

Collection Before After Speedup
SortedList(100k).copy() 59.68 ms 20.08 ms 2.97x faster
SortedKeyList(10k, key=lambda).copy() 61.21 ms 3.06 ms 20.0x faster
SortedDict(10k).copy() 45.60 ms 32.65 ms 1.40x faster

Verification

  • 299/299 tests pass (python -m pytest tests).
  • No changes to public API or semantics.

…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.
@manav4u

manav4u commented Nov 28, 2026

Copy link
Copy Markdown

The fast copy path skips subclass initialization, so a copy can have the right type but be unusable. For example, a default-factory SortedDict:

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 failure

On ee904f1, both raise AttributeError: 'DefaultSortedDict' object has no attribute 'default_factory'. Both work on base 3ac3586. SortedList and SortedKeyList subclasses likewise lose state established in __init__ because of object.__new__.

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.

@millisdoe-glitch

Copy link
Copy Markdown
Author

Thanks for catching that, @manav4u!

You're right — bypassing __init__ via __new__ skipped subclass initialization for SortedDict, SortedList, and SortedKeyList subclasses.

I've updated copy() in all three classes to only take the fast path when type(self) is the exact built-in class (SortedDict, SortedList, or SortedKeyList), falling back to self.__class__(...) for subclasses, and added subclass copy tests in tests/test_coverage_sorteddict.py and tests/test_coverage_sortedlist.py.

All 292/292 coverage tests pass locally (pytest tests/test_coverage_*.py).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants