Instantly share code, notes, and snippets.

Embed
What would you like to do?
My own benchmarks on each_with_object
require 'benchmark'
array = [1, 2, 3]
iterations = 1_000_000
def method_one(array)
hash = {}
array.each do |integer|
hash[integer] = integer ** 2
end
hash
end
def method_two(array)
{}.tap do |hash|
array.each do |integer|
hash[integer] = integer ** 2
end
end
end
def method_three(array)
array.each_with_object({}) do |integer, hash|
hash[integer] = integer ** 2
end
end
Benchmark.bm(7) do |x|
x.report("method one") do
iterations.times do
method_one(array)
end
end
x.report("method two") do
iterations.times do
method_two(array)
end
end
x.report("method three") do
iterations.times do
method_three(array)
end
end
end
# chrisj@scruffy ~/projects $ ruby benchmark.rb
# user system total real
# method one 3.050000 0.010000 3.060000 ( 3.530709)
# method two 3.390000 0.000000 3.390000 ( 3.635153)
# method three 4.120000 0.000000 4.120000 ( 4.400589)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment