Skip to content

Instantly share code, notes, and snippets.

@greyblake
Created January 17, 2012 09:21
Show Gist options
  • Save greyblake/1625824 to your computer and use it in GitHub Desktop.
Save greyblake/1625824 to your computer and use it in GitHub Desktop.
inject, merge, each ...
#!/usr/bin/env ruby
require 'benchmark'
array = (1..10_000).to_a
m = Benchmark.bm(15) do |x|
x.report("inject") do
array.inject({}) do |hash, element|
hash[element] = element
hash
end
end
x.report("inject & merge") do
array.inject({}) do |hash, element|
hash.merge(element => element)
end
end
x.report("each") do
hash = {}
array.each do |element|
hash[element] = element
end
hash
end
end
puts m
# Output:
#
# user system total real
# inject 0.010000 0.000000 0.010000 ( 0.011900)
# inject & merge 7.890000 0.020000 7.910000 ( 7.905326)
# each 0.000000 0.000000 0.000000 ( 0.004576)
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment