Skip to content

Instantly share code, notes, and snippets.

@jmdeldin
Created November 11, 2014 21:30
Show Gist options
  • Save jmdeldin/88cbd2ba852819cd6d52 to your computer and use it in GitHub Desktop.
Save jmdeldin/88cbd2ba852819cd6d52 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
Cart = Struct.new(:items)
N = 10_000
query = -> { Array.new(N).map { |a| Cart.new(%w(foo bar baz)) } }
Benchmark.ips do |x|
x.report('each') do
carts = query.()
results = []
carts.each do |cart|
cart.items.each do |item|
results << {name: item}
end
end
end
x.report('flat_map') do
carts = query.()
carts.flat_map do |cart|
cart.items.map! { |item| {name: item} }
end
end
x.report('map_flatten') do
carts = query.()
carts.map! do |cart|
cart.items.map! { |item| {name: item} }
end.flatten!
end
x.report('reduce') do
carts = query.()
carts.reduce([]) do |ary, cart|
cart.items.each { |item| ary << {name: item} }
ary
end
end
x.report('each_with_object') do
carts = query.()
carts.each_with_object([]) do |cart, ary|
cart.items.each { |item| ary << {name: item} }
end
end
end
# -*- mode: ruby-compilation; default-directory: "~/src/sandbox/" -*-
# RubyComp started at Tue Nov 11 13:29:01
#
# ruby /home/jmdeldin/src/sandbox/fastest_map_hash.rb
# Calculating -------------------------------------
# each 6 i/100ms
# flat_map 6 i/100ms
# map_flatten 6 i/100ms
# reduce 6 i/100ms
# each_with_object 6 i/100ms
# -------------------------------------------------
# each 70.6 (±9.9%) i/s - 354 in 5.060102s
# flat_map 64.9 (±3.1%) i/s - 330 in 5.088580s
# map_flatten 60.4 (±8.3%) i/s - 300 in 5.004533s
# reduce 69.4 (±10.1%) i/s - 348 in 5.064078s
# each_with_object 68.3 (±7.3%) i/s - 342 in 5.036201s
#
# RubyComp finished at Tue Nov 11 13:29:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment