Skip to content

Instantly share code, notes, and snippets.

@dharamgollapudi
Forked from PragTob/benchmark.rb
Created May 21, 2018 06:58
Show Gist options
  • Save dharamgollapudi/6d7ca8e828681b451424f6a3e3ba3e24 to your computer and use it in GitHub Desktop.
Save dharamgollapudi/6d7ca8e828681b451424f6a3e3ba3e24 to your computer and use it in GitHub Desktop.
Ruby flat_map vs. map.flatten
require 'benchmark/ips'
Benchmark.ips do |bm|
list = (0..10_000).to_a
bm.report "flat_map" do
list.flat_map do |x|
[x, x * x]
end
end
bm.report "map.flatten" do
list.map do |x|
[x, x * x]
end.flatten
end
bm.compare!
end
tobi@happy ~/github/ruby_playground $ ruby benchmark/flat_map.rb
Warming up --------------------------------------
flat_map 95.000 i/100ms
map.flatten 42.000 i/100ms
Calculating -------------------------------------
flat_map 972.133 (± 5.1%) i/s - 4.845k in 5.002625s
map.flatten 423.280 (± 2.4%) i/s - 2.142k in 5.063801s
Comparison:
flat_map: 972.1 i/s
map.flatten: 423.3 i/s - 2.30x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment