forked from fastruby/fast-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-keys-vs-symbol-keys-with-1000-pairs.rb
57 lines (42 loc) · 1.28 KB
/
string-keys-vs-symbol-keys-with-1000-pairs.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require "benchmark/ips"
STRING_KEYS = (1001..2000).map{|x| "key_#{x}"}.shuffle
FROZEN_KEYS = (2001..3000).map{|x| "key_#{x}".freeze}.shuffle
SYMBOL_KEYS = (3001..4000).map{|x| "key_#{x}".to_sym}.shuffle
# If we use static values for Hash, speed improves even more.
def symbol_hash
SYMBOL_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
def string_hash
STRING_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
# See this article for the discussion of using frozen strings instead of symbols
# http://blog.arkency.com/could-we-drop-symbols-from-ruby/
def frozen_hash
FROZEN_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
SYMBOL_HASH = symbol_hash
STRING_HASH = string_hash
FROZEN_HASH = frozen_hash
def reading_symbol_hash
SYMBOL_HASH[SYMBOL_KEYS.sample]
end
def reading_string_hash
STRING_HASH[STRING_KEYS.sample]
end
def reading_frozen_hash
FROZEN_HASH[FROZEN_KEYS.sample]
end
Benchmark.ips do |x|
puts "Creating large Hash"
x.report("Symbol Keys") { symbol_hash }
x.report("String Keys") { string_hash }
x.report("Frozen Keys") { frozen_hash }
x.compare!
end
Benchmark.ips do |x|
puts "Reading large Hash"
x.report("Symbol Keys") { reading_symbol_hash }
x.report("String Keys") { reading_string_hash }
x.report("Frozen Keys") { reading_frozen_hash }
x.compare!
end