Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Created May 2, 2019 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lavoiesl/070f16d83afd440a14ba865e5fe8bc23 to your computer and use it in GitHub Desktop.
Save lavoiesl/070f16d83afd440a14ba865e5fe8bc23 to your computer and use it in GitHub Desktop.
Ruby each vs each_with_object vs inject
require 'benchmark'
size = 100
list = []
size.times { |i| list << {name: "item #{i}"} }
n = 5000
Benchmark.bmbm(16) do |bm|
bm.report('each_with_object') { n.times { list.each_with_object({}) { |item, map| map[item[:name]] = item } } }
bm.report('inject+merge') { n.times { list.inject({}) { |map, item| map.merge(item[:name] => item) } } }
bm.report('inject+assign') { n.times { list.inject({}) { |map, item| map[item[:name]] = item; map } } }
bm.report('each') { n.times { map = {}; list.each { |item| map[item[:name]] = item } } }
end
# size = 10
# user system total real
# each_with_object 0.020000 0.000000 0.020000 ( 0.019710)
# inject+merge 0.140000 0.000000 0.140000 ( 0.151981)
# inject+assign 0.020000 0.000000 0.020000 ( 0.021939)
# each 0.020000 0.000000 0.020000 ( 0.018951)
# size = 100
# user system total real
# each_with_object 0.210000 0.000000 0.210000 ( 0.205544)
# inject+merge 11.870000 0.190000 12.060000 ( 12.261768)
# inject+assign 0.200000 0.000000 0.200000 ( 0.202474)
# each 0.180000 0.010000 0.190000 ( 0.190451)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment