Skip to content

Commit 7d2dbc2

Browse files
authored
Merge pull request #247 from fastruby/feature/adopt-open-prs-4
Adopt the last open benchmark PR
2 parents 3ff4aba + 0601a80 commit 7d2dbc2

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
require 'benchmark/ips'
2+
3+
# The same 1000 keys, as Symbols, frozen Strings and plain Strings, each mapped to its index.
4+
SYMBOL_KEYS = (1..1000).map { |i| :"key_#{i}" }
5+
FROZEN_KEYS = (1..1000).map { |i| "key_#{i}".freeze }
6+
STRING_KEYS = (1..1000).map { |i| "key_#{i}" }
7+
8+
def build(keys)
9+
keys.each_with_index.map { |key, index| [key, index] }.to_h
10+
end
11+
12+
# Symbol and frozen String keys tie on Ruby 4.0.
13+
def faster
14+
build(SYMBOL_KEYS)
15+
end
16+
17+
# A Hash copies and freezes a plain String key, but keeps a frozen one as it is.
18+
def fast
19+
build(FROZEN_KEYS)
20+
end
21+
22+
def slow
23+
build(STRING_KEYS)
24+
end
25+
26+
Benchmark.ips do |x|
27+
x.report('Symbol Keys') { faster }
28+
x.report('Frozen Keys') { fast }
29+
x.report('String Keys') { slow }
30+
x.compare!
31+
end
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
require 'benchmark/ips'
2+
3+
# The same 1000 keys, as Symbols, frozen Strings and plain Strings, each mapped to its index.
4+
SYMBOL_KEYS = (1..1000).map { |i| :"key_#{i}" }
5+
FROZEN_KEYS = (1..1000).map { |i| "key_#{i}".freeze }
6+
STRING_KEYS = (1..1000).map { |i| "key_#{i}" }
7+
8+
SYMBOL_HASH = SYMBOL_KEYS.each_with_index.map { |key, index| [key, index] }.to_h
9+
FROZEN_HASH = FROZEN_KEYS.each_with_index.map { |key, index| [key, index] }.to_h
10+
STRING_HASH = STRING_KEYS.each_with_index.map { |key, index| [key, index] }.to_h
11+
12+
# Reads every key once.
13+
def faster
14+
SYMBOL_KEYS.each { |key| SYMBOL_HASH[key] }
15+
end
16+
17+
def fast
18+
FROZEN_KEYS.each { |key| FROZEN_HASH[key] }
19+
end
20+
21+
def slow
22+
STRING_KEYS.each { |key| STRING_HASH[key] }
23+
end
24+
25+
Benchmark.ips do |x|
26+
x.report('Symbol Keys') { faster }
27+
x.report('Frozen Keys') { fast }
28+
x.report('String Keys') { slow }
29+
x.compare!
30+
end

0 commit comments

Comments
 (0)