Project

General

Profile

Feature #15251 » bench_hash_aset.rb

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

 
require 'benchmark'

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

def random_text
str = ''
length = rand(5..34)
while (length -= 1) > 0
str << CharSet.sample
end
str
end

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

ARR_SIZE = literal_arr.size

ARR_SIZE_TIMES = ARR_SIZE.times

def random_text
CharSet.sample(15).join
end

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

def random_arr
Array.new(20) { random_text }
end

def highlight(text)
puts '-+' * 20
puts text
puts '-+' * 20
end

N = 100_000

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

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

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

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

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