Skip to content

Instantly share code, notes, and snippets.

@Spaceghost
Created December 16, 2014 06:01
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 Spaceghost/780565d7ffe03f9f77df to your computer and use it in GitHub Desktop.
Save Spaceghost/780565d7ffe03f9f77df to your computer and use it in GitHub Desktop.

In map.rb, map is far faster.

In each_with_object.rb, each_with_object is just a tiny bit faster than assign & return.

require 'benchmark/ips'
User = Struct.new(:id, :stuff)
a = Array.new(1000) { |i| User.new(i, stuff: rand(1000)) }
Benchmark.ips do |x|
x.report('#inject assign&return') do
a.inject({}) { |memo, i| memo[i.id] = i.stuff; memo }
end
x.report('merge') do
a.inject({}) { |memo, i| memo.merge(i.id => i.stuff) }
end
x.report('merge!') do
a.inject({}) { |memo, i| memo.merge!(i.id => i.stuff) }
end
x.report('each_with_object') do
a.each_with_object({}) { |i, memo| memo[i.id] = i.stuff }
end
end
require 'benchmark/ips'
User = Struct.new(:id, :stuff)
a = Array.new(1000) { |i| User.new(i, stuff: rand(1000)) }
Benchmark.ips do |x|
x.report('#map') do
a.map(&:stuff)
end
x.report('#each_with_object') do
a.each_with_object([]) do |user, collection|
collection << user.stuff
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment