Skip to content

Instantly share code, notes, and snippets.

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

Benchmarking #map

#map(&:id) is faster than a block.
#map is faster than #each_with_object when doing roughly the same work.

In short, this might make you want to extract more public methods, even if you use them in decorators or proxy objects, that you can call with Symbol#to_proc.

require 'benchmark/ips'
User = Struct.new(:id)
a = Array.new(1000) { |i| User.new(i) }
Benchmark.ips do |x|
x.report('#each_with_object') do
a.each_with_object([]) do |i, a|
a << i.id
end
end
x.report('#map') do
a.map do |i|
i.id
end
end
x.report('#map(&:id)') do
a.map(&:id)
end
end
Calculating -------------------------------------
#each_with_object 775.000 i/100ms
#map 1.381k i/100ms
#map(&:id) 1.851k i/100ms
-------------------------------------------------
#each_with_object 8.082k (± 3.6%) i/s - 41.075k
#map 14.547k (± 3.5%) i/s - 73.193k
#map(&:id) 19.841k (± 3.5%) i/s - 99.954k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment