Project

General

Profile

Feature #15251 ยป bench_hash_aset.rb

chopraanmol1 (Anmol Chopra), 10/25/2018 06:56 AM

 
1
require 'benchmark'
2

    
3
CharSet = ['a'..'z', '0'..'9', 'A'..'Z'].flat_map(&:to_a)
4

    
5
def random_text
6
  str = ''
7
  length = rand(5..34)
8
  while (length -= 1) > 0
9
    str << CharSet.sample
10
  end
11
  str
12
end
13

    
14
def literal_arr
15
  @literal ||= %w[text1 text2 text3 text4 text5 text6 text7 text8 text9 text10 text11 text12 text13 text14 text15 text16 text17 text18 text19 text20]
16
end
17

    
18
ARR_SIZE = literal_arr.size
19

    
20
ARR_SIZE_TIMES = ARR_SIZE.times
21

    
22
def random_text
23
  CharSet.sample(15).join
24
end
25

    
26
def non_literal_arr
27
  @non_literal ||= Array.new(ARR_SIZE) { random_text }
28
end
29

    
30
def random_arr
31
  Array.new(20) { random_text }
32
end
33

    
34
def highlight(text)
35
  puts '-+' * 20
36
  puts text
37
  puts '-+' * 20
38
end
39

    
40
N = 100_000
41

    
42
highlight 'Hash#[`string literal`.dup]='
43
puts Benchmark.measure { N.times { hsh = {}; literal_arr.each { |str| hsh[str.dup] = 0 } } }
44

    
45
highlight 'Hash#[`string non-literal`.dup]='
46
puts Benchmark.measure { N.times { hsh = {}; non_literal_arr.each { |str| hsh[str.dup] = 0 } } }
47

    
48
highlight 'Hash#[`random text`]='
49
puts Benchmark.measure { N.times { hsh = {}; ARR_SIZE_TIMES.each { hsh[random_text] = 0 } } }
50

    
51
highlight 'Hash#[`string literal`.dup]='
52
puts Benchmark.measure { N.times { hsh = {}; literal_arr.each { |str| hsh[str.dup] = 0 } } }
53

    
54
highlight 'Hash#[`string non-literal`.dup]='
55
puts Benchmark.measure { N.times { hsh = {}; non_literal_arr.each { |str| hsh[str.dup] = 0 } } }