Skip to content

Evicting oldest-first from InsertionOrderMap/ContiguousMap is quadratic: emptying a 40k map takes ~3.6 s #101

Open

Description

@matt-edmondson

What's wrong

Remove(TKey) on both insertion-ordered maps rewrites the key→index dictionary for every entry after the removed one:

  • Containers/InsertionOrderMap.cs:283-288: for (i = index; i < items.Count; i++) keyToIndex[items[i].Key] = i;
  • Containers/ContiguousMap.cs:375-410 (loop at ~:404): same pattern.

Remove is documented as O(n), but the O(n) here is a hash lookup+write per shifted element rather than a memmove, and it is hit worst by the most natural use of an insertion-order map: evicting the oldest key (LRU/FIFO caches), which shifts every remaining entry.

Measured (Release; remove keys 0..n-1 in insertion order)

n InsertionOrderMap ContiguousMap Dictionary
10k 301 ms 277 ms 0 ms
20k 893 ms 919 ms 0 ms
40k 3572 ms 3708 ms 0 ms

4× per doubling, so quadratic; ~22 s extrapolated at 100k.

Suggested fix / acceptance criteria

  • InsertionOrderMap (no span API, so layout is free): tombstone removed slots and compact + reindex once tombstones exceed ~half the list, giving amortised O(1) Remove while preserving order. Enumeration and IVersionedEntries.KeyAt/ValueAt must skip tombstones (or compact before enumerating).
  • ContiguousMap (contiguity/AsSpan must hold): at minimum add a bulk RemoveWhere(Predicate<...>)/RemoveRange that compacts and reindexes once (O(n) total); optionally a head offset to make removing index 0 cheap.
  • Add a benchmark removing oldest-first at n = 100k.

Distinct from #82 (Ordered* bulk construction) and #83 (ContiguousSet/InsertionOrderSet set operations).

Activity

  1. added
    enhancement
    on Oct 6, 2026
  2. matt-edmondson commented on Oct 6, 2026

    @matt-edmondson
    ContributorAuthor

    Triage

    Recommended next step: Do the InsertionOrderMap tombstone and amortised-compaction fix first, because it has no layout constraint. Then add RemoveWhere/RemoveRange to ContiguousMap, and add the 100k oldest-first benchmark.


    Generated by Claude Code

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions