Skip to content

Optimize Keyword.validate/2 to avoid building new list#15269

Merged
sabiwara merged 1 commit intoelixir-lang:mainfrom
sabiwara:optimize-kw-validate
Apr 14, 2026
Merged

Optimize Keyword.validate/2 to avoid building new list#15269
sabiwara merged 1 commit intoelixir-lang:mainfrom
sabiwara:optimize-kw-validate

Conversation

@sabiwara
Copy link
Copy Markdown
Contributor

Maybe I'm missing something, but as far as I can tell, there is no need to re-build that kw-list, since in the case there is a "bad_key" we're not using the acc anyway?
So we just end up reversing the list for no reason - this new version just returns the original as is, which is less work:

# main
iex> Keyword.validate!([a: 1, b: 2], [:a, :b])
[b: 2, a: 1]
# this branch
iex> Keyword.validate!([a: 1, b: 2], [:a, :b])
[a: 1, b: 2]

Confirmed with a quick benchmark that this reduces the memory footprint:

Comparison: 
candidate        7.63 M
original         6.76 M - 1.13x slower +16.80 ns

Memory usage statistics:

Name         Memory usage
candidate           264 B
original            424 B - 1.61x memory usage +160 B

@sabiwara sabiwara merged commit 20cd669 into elixir-lang:main Apr 14, 2026
15 checks passed
@sabiwara sabiwara deleted the optimize-kw-validate branch April 14, 2026 22:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants