Skip to content

Instantly share code, notes, and snippets.

@PragTob
Created June 6, 2016 17:49
Show Gist options
  • Save PragTob/8f037b6cab4bffca411063aced6a7917 to your computer and use it in GitHub Desktop.
Save PragTob/8f037b6cab4bffca411063aced6a7917 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