Skip to content

perf: reverse_purge_hash_map::purge no longer allocates its sample - #560

Open
rustyconover wants to merge 1 commit into
apache:masterfrom
rustyconover:perf/frequent-items-purge-stack
Open

rustyconover wants to merge 1 commit into
apache:masterfrom
rustyconover:perf/frequent-items-purge-stack

Conversation

@rustyconover

Copy link
Copy Markdown

To find the median weight, reverse_purge_hash_map::purge() allocates and frees an array of up to MAX_SAMPLE_SIZE (1024) values through the sketch's allocator on every purge. A sketch over a long stream of distinct items purges constantly, so that's one allocation per purge.

This keeps the sample on the stack instead: V samples[MAX_SAMPLE_SIZE], which is 8 KB for 64-bit weights. A purge then makes no allocation. If 8 KB of stack is more than you'd like for this path, I can change it to a buffer the map keeps for reuse.

Test

Added frequent items: a purge does not allocate to frequent_items_sketch_custom_type_test.cpp. It uses an allocator that counts allocate() calls, starts the map at its maximum size so it only purges, and streams 99,000 distinct items after warming up. Without the change it makes 3,960 allocations, one per purge; with it, none. All frequent-items tests pass.

We found this in the DuckDB DataSketches extension. There, sketches allocate from DuckDB's per-query arena, which doesn't take back individual frees, so each purge's array was memory the arena never got back.

🤖 Generated with Claude Code

Every purge allocated, and freed, an array of up to MAX_SAMPLE_SIZE (1024)
values through the sketch's allocator to find the median. Keep it on the
stack instead (8 KB for 64-bit weights), so a purge makes no allocation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant