Skip to content

Use Symbol#name for session key stringification - #59102

Merged
amatsuda merged 1 commit into
rails:mainfrom
amatsuda:session-key-symbol-name
Oct 15, 2026
Merged

amatsuda merged 1 commit into
rails:mainfrom
amatsuda:session-key-symbol-name

Conversation

@amatsuda

Copy link
Copy Markdown
Member

Motivation / Background

The session accessors call key.to_s on every access. Virtually every caller passes a symbol (session[:user_id], the CSRF token, the flash), and Symbol#to_s allocates a new String on every call on every released Ruby from 3.3 to 4.0. Symbol#name returns the symbol's interned frozen string instead, which is also exactly what Hash#[]= would have made of the key.

Detail

The conversion is factored into a private stringify_key and used at all seven call sites: [], []=, dig, has_key?, delete and both arms of fetch. String keys are unaffected, since String#to_s returns self.

A test pins that symbol and string keys address the same entry through writes, reads, key? and delete, which only fetch and dig covered before.

Additional information

Measured on Ruby 3.4.11 for the key conversion plus the hash lookup it feeds:

before after
allocations per access 1 0
5,000,000 accesses 0.46s 0.30s

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Unrelated changes should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

🤖 Generated with Claude Code

The session accessors call key.to_s on every access. Virtually every
caller passes a symbol (session[:user_id], the CSRF token, the flash),
and Symbol#to_s allocates a new String on every call on every released
Ruby from 3.3 to 4.0. Symbol#name returns the symbol's interned frozen
string instead, which is also exactly what Hash#[]= would have made of
the key.

Factor the conversion into a private stringify_key and use it at all
seven call sites. String keys are unaffected: String#to_s returns self.

Measured on Ruby 3.4.11 for the key conversion plus the hash lookup it
feeds:

  allocations per access   1 -> 0
  5,000,000 accesses       0.46s -> 0.30s

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@amatsuda
amatsuda merged commit 85dbd08 into rails:main Oct 15, 2026
5 checks passed
@amatsuda
amatsuda deleted the session-key-symbol-name branch October 15, 2026 14:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant