Кому-то эти нюансы, вероятно известны, а кому-то будут интересны. Коротко: помните о существовании Set, each_value, find. - производительность от этого может вырасти в разы. Так же, удобная штука - использование скобок в параметрах блоков.
require 'set'
a = []
s = Set.new
h = {}
n = 10000
Benchmark.bm(3) do |b|
puts 'add'
b.report("array:"){ 200.times{|i| a << i } }
b.report("set :"){ 200.times{|i| s << i } }
b.report("hash :"){ 200.times{|i| h[:"#{i}"] = i } }
puts 'include?'
b.report("array:"){ 200.times{|i| a.include? i } }
b.report("set :"){ 200.times{|i| s.include? i } }
puts 'inject'
b.report("array:"){ n.times{|i| a.inject(0){|s, v| s + v } } }
b.report("set :"){ n.times{|i| s.inject(0){|s, v| s + v } } }
b.report("hash :"){ n.times{|i| h.inject(0){|s, ( k, v )| s + v } } }
b.report("hash :"){ n.times{|i| h.each_value.inject(0){|s, v| s + v } } }
b.report("hash :"){ n.times{|i| h.inject(0){|s, v| s + v.last } } }
puts 'find'
b.report("array:"){ n.times{|i| a.find{|el| el == 150 } } }
b.report("set :"){ n.times{|i| s.find{|el| el == 150 } } }
b.report("hash :"){ n.times{|i| h[:"150"] } }
puts 'each'
b.report("array:"){ n.times{|i| a.each &:to_s } }
b.report("set :"){ n.times{|i| s.each &:to_s } }
b.report("hash :"){ n.times{|i| h.each_value &:to_s } }
b.report("hash :"){ n.times{|i| h.each{|k,v| v.to_s } } }
puts 'map'
b.report("array:"){ n.times{|i| a.map &:to_s } }
b.report("set :"){ n.times{|i| s.map &:to_s } }
b.report("hash :"){ n.times{|i| h.each_value.map &:to_s } }
b.report("hash :"){ n.times{|i| h.map{|k,v| v.to_s } } }
end
результат на mri
user system total real
add
array: 0.000000 0.000000 0.000000 ( 0.000043)
set : 0.000000 0.000000 0.000000 ( 0.000103)
hash : 0.000000 0.000000 0.000000 ( 0.000344)
include?
array: 0.000000 0.000000 0.000000 ( 0.000877)
set : 0.000000 0.000000 0.000000 ( 0.000060)
inject
array: 0.230000 0.000000 0.230000 ( 0.226024)
set : 0.290000 0.010000 0.300000 ( 0.298473)
hash : 0.490000 0.000000 0.490000 ( 0.487521)
hash : 0.270000 0.000000 0.270000 ( 0.287539)
hash : 0.490000 0.000000 0.490000 ( 0.497619)
find
array: 0.140000 0.000000 0.140000 ( 0.142135)
set : 0.200000 0.000000 0.200000 ( 0.198234)
hash : 0.000000 0.000000 0.000000 ( 0.000974)
each
array: 0.380000 0.000000 0.380000 ( 0.384158)
set : 0.460000 0.000000 0.460000 ( 0.453658)
hash : 0.450000 0.010000 0.460000 ( 0.457729)
hash : 0.670000 0.000000 0.670000 ( 0.672617)
map
array: 0.430000 0.000000 0.430000 ( 0.430366)
set : 0.570000 0.000000 0.570000 ( 0.572334)
hash : 0.550000 0.000000 0.550000 ( 0.558118)
hash : 0.800000 0.010000 0.810000 ( 0.796961)
