mirror of
https://github.com/ruby/ruby.git
synced 2025-08-15 05:29:10 +02:00

[Feature #19236]
When building a large hash, pre-allocating it with enough
capacity can save many re-hashes and significantly improve
performance.
```
/opt/rubies/3.3.0/bin/ruby --disable=gems -rrubygems -I./benchmark/lib ./benchmark/benchmark-driver/exe/benchmark-driver \
--executables="compare-ruby::../miniruby-master -I.ext/common --disable-gem" \
--executables="built-ruby::./miniruby --disable-gem" \
--output=markdown --output-compare -v $(find ./benchmark -maxdepth 1 -name 'hash_new' -o -name '*hash_new*.yml' -o -name '*hash_new*.rb' | sort)
compare-ruby: ruby 3.4.0dev (2024-03-25T11:48:11Z master f53209f023
) +YJIT dev [arm64-darwin23]
last_commit=[ruby/irb] Cache RDoc::RI::Driver.new (https://github.com/ruby/irb/pull/911)
built-ruby: ruby 3.4.0dev (2024-03-25T15:29:40Z hash-new-rb 77652b08a2) +YJIT dev [arm64-darwin23]
warming up...
| |compare-ruby|built-ruby|
|:-------------------|-----------:|---------:|
|new | 7.614M| 5.976M|
| | 1.27x| -|
|new_with_capa_1k | 13.931k| 15.698k|
| | -| 1.13x|
|new_with_capa_100k | 124.746| 148.283|
| | -| 1.19x|
```
16 lines
542 B
YAML
16 lines
542 B
YAML
prelude: |
|
|
has_hash_with_capa = Hash.instance_method(:initialize).parameters.include?([:key, :capacity])
|
|
strings_1k = 1_000.times.map { |i| -i.to_s.freeze }
|
|
strings_100k = 100_000.times.map { |i| -i.to_s.freeze }
|
|
benchmark:
|
|
new: Hash.new
|
|
new_with_capa_1k: |
|
|
h = has_hash_with_capa ? Hash.new(capacity: strings_1k.size) : {}
|
|
strings_1k.each do |x|
|
|
h[x] = true
|
|
end
|
|
new_with_capa_100k: |
|
|
h = has_hash_with_capa ? Hash.new(capacity: strings_100k.size) : {}
|
|
strings_100k.each do |x|
|
|
h[x] = true
|
|
end
|