perf: O(log n) sorted set rank and incremental memory tracking#224
Merged
perf: O(log n) sorted set rank and incremental memory tracking#224
Conversation
the previous implementation used a BTreeMap for score-ordered storage, making rank() O(n) — it counted elements with range(..).count() which walks every node up to the target. for a leaderboard with 100k members, ZRANK required 100k comparisons. the new implementation uses a sorted Vec instead: - rank() is now O(log n) via binary_search_by - range_by_rank() is a simple slice instead of skip()+take() over a btree - iteration is more cache-friendly (contiguous memory vs pointer-chasing) - each member costs ~24 bytes for the Vec slot vs ~64 for a BTreeMap node the tradeoff is O(n) insert/remove (Vec shifting), but Vec's memmove is cache-friendly and faster than BTreeMap's O(log n) with high constant factor for typical sorted set sizes. also adds data_bytes: usize to cache the sum of member string lengths, making memory_usage() O(1) rather than iterating all members on every call.
every list push or pop previously called entry_size() twice (before and after the mutation), each of which iterates all elements in the VecDeque to sum their lengths. for a list with 10k elements, a single LPUSH triggered 20k iterations just for memory accounting. the fix is to use the element delta that is already computed: - list_push: element_increase is precomputed for reserve_memory; apply it directly with memory.grow_by() instead of calling track_size() - list_pop: the popped element's size is known; apply it directly with memory.shrink_by() for non-empty lists, or compute exact old_size from constants for the empty-list removal path — no list scan at either step - zrem, hdel, srem: capture the byte cost of each actually-removed member/field while iterating, then pass it to cleanup_after_remove() so the second O(n) rescan is eliminated adds MemoryTracker::grow_by() and shrink_by() for callers that know their exact delta. cleanup_after_remove() now takes removed_bytes instead of rescanning the remaining collection. sorted set mutations were already improved by the SortedSet rewrite (memory_usage() is now O(1) there).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
summary
two related improvements to data structure performance:
sorted set rank: O(n) → O(log n)
the previous
rank()usedBTreeMap::range(..key).count()which walks every node up to the target — O(n) for a 100k-member leaderboard. the BTreeMap has been replaced with a sortedVec<(OrderedFloat<f64>, Arc<str>)>, makingrank()a binary search: O(log n).range_by_rank()is also simplified — it's a plain slice rather thanskip(n).take(m)over a BTreeMap iterator. the Vec is more cache-friendly for iteration.as a side effect, each member now costs ~24 bytes for its Vec slot vs ~64 for a BTreeMap node. the tradeoff is O(n) Vec insert/remove, but cache-friendly memmove is faster than BTreeMap pointer-chasing for typical sorted set sizes.
also adds a
data_bytesfield that caches the sum of member string lengths, makingmemory_usage()O(1) rather than iterating all members on every mutation.incremental memory tracking for collection mutations
every list push/pop previously called
entry_size()twice (before and after the mutation), each of which iterates all elements in the VecDeque. for a 10k-element list, a single LPUSH triggered 20k element-scans just for memory bookkeeping.the fix uses the delta that is already computed:
list_push: the total element increase is precomputed forreserve_memory; it's now applied withmemory.grow_by()instead oftrack_size()list_pop: the popped element size is known; no scan needed for either the shrink or the removal pathzrem,hdel,srem: capture the byte cost of each actually-removed entry while iterating, eliminating the rescan incleanup_after_remove()adds
MemoryTracker::grow_by()/shrink_by()for callers that know their exact delta.what was tested
cargo test -p emberkv-core: 344 passedcargo test -p ember-server: 105 passedcargo test -p ember-cluster: 105 passeddesign considerations
the Vec-based sorted set is a good fit for the insert-heavy but read-many access pattern common in leaderboards: inserts pay O(n) shifting, but rank and range queries (which are often more frequent in read-heavy workloads) pay O(log n) and O(k) respectively. for workloads that are pure ZADD-heavy with rare ZRANK, the BTreeMap would be faster — this is worth revisiting if profiling shows otherwise.