| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
Builds on the idea from #124 (sFrenkie), comparing three ways to collect the non-nil values of a hash: - Hash#select { |_k, v| v }.values - Hash#values.select { |v| v } - Hash#values.compact Uses data that actually contains nil values so all three return the same result, plus an equivalence guard, making it a fair comparison. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
This PR adds a new Hash performance benchmark to fairly compare three equivalent ways of collecting non-nil hash values, and documents the results in the README’s Hash section.
Changes:
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| README.md | Adds a Hash section entry documenting the benchmark and explaining why values.compact is fastest. |
| code/hash/select-values-vs-values-select-vs-values-compact.rb | Introduces the benchmark implementation plus an equivalence guard to ensure fair comparison. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Sorry, something went wrong.
| def select_values | ||
| HASH.select { |_k, v| v }.values | ||
| end |
| def values_select | ||
| HASH.values.select { |v| v } | ||
| end |
| # Sanity check: all three must return the same values. | ||
| raise "not equivalent" unless select_values.sort == values_select.sort && | ||
| values_select.sort == values_compact.sort |
| > To collect the non-nil values of a hash, `Hash#select { |_k, v| v }.values` allocates an intermediate hash before extracting its values; <br> | ||
| > `Hash#values.select { |v| v }` skips the intermediate hash but still runs a block per element; <br> |
| Back | FazBrowse Home | New Git URL |
What
Adds a Hash benchmark comparing three ways to collect the non-nil values of a hash:
Hash#values.compact wins by a wide margin (~16x faster than values.select).
Why a new PR instead of #124
This builds on the idea from #124 by @sFrenkie, but that benchmark's three expressions aren't equivalent: its test data uses boolean values (v < 0.5 → true/false) and contains no nil values. So compact filtered nothing while the two select variants also dropped false. The "fastest" result came from compact doing less work, not from a fair comparison.
This version fixes that:
Output
README entry added in the Hash section.
🤖 Generated with Claude Code