# Pastebin RVBJ1IgP # frozen-string-literal: true require 'benchmark' str = 'AGTCAGTCAGTCTTTCCCAAAT' keys = %w[A C G T] n = 100000 Benchmark.bmbm do |x| x.report('count') { n.times{ keys.map{|e| [e, str.count(e)] }.to_h } } x.report('reduce') { n.times{ str.chars.reduce(Hash.new(0)){|a,c|a[c]+=1;a} } } x.report('group_by') { n.times{ str.chars.group_by(&:itself).map{|k,v|[k,v.size]}.to_h } } end str = 'AGTCAGTCAGTCTTTCCCAAAT'.encode('US-ASCII') * 1000 keys = %w[A C G T] n = 1000 Benchmark.bmbm do |x| x.report('large count') { n.times{ keys.map{|e| [e, str.count(e)] }.to_h } } x.report('large reduce') { n.times{ str.chars.reduce(Hash.new(0)){|a,c|a[c]+=1;a} } } x.report('large group_by') { n.times{ str.chars.group_by(&:itself).map{|k,v|[k,v.size]}.to_h } } end __END__ Rehearsal -------------------------------------------- count 0.120000 0.000000 0.120000 ( 0.126792) reduce 0.590000 0.000000 0.590000 ( 0.588076) group_by 0.690000 0.000000 0.690000 ( 0.690314) ----------------------------------- total: 1.400000sec user system total real count 0.110000 0.000000 0.110000 ( 0.109941) reduce 0.560000 0.000000 0.560000 ( 0.568418) group_by 0.660000 0.000000 0.660000 ( 0.667988) Rehearsal -------------------------------------------------- large count 0.050000 0.000000 0.050000 ( 0.041615) large reduce 4.770000 0.000000 4.770000 ( 4.784031) large group_by 3.940000 0.010000 3.950000 ( 3.946272) ----------------------------------------- total: 8.770000sec user system total real large count 0.050000 0.000000 0.050000 ( 0.043490) large reduce 4.720000 0.000000 4.720000 ( 4.723694) large group_by 3.940000 0.000000 3.940000 ( 3.944049)