Skip to content

Avoid creating String for every key - #71

Merged
jho406 merged 1 commit into
mainfrom
perf-improve-obj-allocations
Oct 17, 2026
Merged

jho406 merged 1 commit into
mainfrom
perf-improve-obj-allocations

Conversation

@jho406

@jho406 jho406 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

format_key called to_s, which returns a new String each time, so every key emitted allocated one. Symbol#name returns the internal allocated frozen String. Its been available since Ruby 3.0, and since we've pinned it to 3.3 +, we're can treat this as a patch.

Improvements are great. I'm looking at a 50% decrease in the number of allocation using alba benchmarks.

format_key called Symbol#to_s, which returns a new String on every call,
so each key emitted allocated one. Symbol#name returns the frozen String
Ruby already keeps for the Symbol instead, so repeated keys allocate
nothing. String keys still go through to_s, which returns them as-is.

Symbol#name has been available since Ruby 3.0, and the gemspec requires
3.3 or later.

On alba's collection benchmark this cuts allocations per render from
7,923 to 3,523 objects (-56%).
@jho406
jho406 force-pushed the perf-improve-obj-allocations branch from d060d09 to 2862404 Compare October 17, 2026 21:12
@jho406
jho406 merged commit 69d36ca into main Oct 17, 2026
24 checks passed
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