Hi, before I enter the deeper QA / quality stage, I want to share with you my results and get some feedback. Recently I started to do something I wanted to do a long time ago: sorted sets are a nice data structure but extremely wasteful memory-wise, it is true that we have a compact representation for small sorted sets, but the value of sorted sets is often in very big or even huge sorted sets, for global scoring of some business logic.
So I implemented two fundamental changes: specialize the hash table for the entry -> metadata lookup, and modify the skiplist implementation to use macro nodes holding multiple elements in a single allocation.
How the hash table works.
The trick used is to store the element string only in the skiplist. The hash table becomes buckets of N entries each that have a 8 bit checksum for quick refusal, and a pointer to the skiplist node of that entry.
How the new skiplist works
On the skiplist side instead of having one allocation per entry, one node stores several elements, scores, strings,... So of course this forces us to some scanning, but thanks to memory locality and having to scan less nodes, we are more the compensated.
Give me the numbers!
- 1M integer-like members, ordered scores: 85.7 MB -> 34.4 MB (-59.9%)
- After 100k random score updates: 85.7 MB -> 36.9 MB (-56.9%)
For longer random members, the string bytes are a larger part of the total object, so the percentage saving is smaller but still large:
- 1M random alphanumeric members, 8..40 bytes, random scores: 111.3 MB -> 64.7 MB (-41.8%)
- After 100k random score updates: 111.3 MB -> 67.6 MB (-39.3%)
After the updates the new code will glue adjacent nodes, but some efficiency is lost anyway.
However this patch has a very nice property, it is a bit faster:
1M random 8..40 byte members:
ZADD: 3.03s -> 2.90s
ZSCORE: 0.360s -> 0.359s
ZRANGE: 0.0338s -> 0.0328s
score updates: 0.437s -> 0.391s
So the question here is, how do we feel about extra complexity and a specialized hash table? I'm ok with it, because of AI and the kind of testing I'll be able to do. But I want the maintainers opinions as well before submitting a PR.
git diff summary: Summary:
12 files changed, 2577 insertions(+), 714 deletions(-)
src/t_zset.c: 2956 lines of diff