Skip to content

Instantly share code, notes, and snippets.

@britishtea
Created December 6, 2012 23:58
Show Gist options
  • Save britishtea/4229547 to your computer and use it in GitHub Desktop.
Save britishtea/4229547 to your computer and use it in GitHub Desktop.
#map { ... }.flatten vs #flat_map
require 'benchmark'
arr = 1_000.times.map { (1..100).to_a }
Benchmark.bm 9 do |x|
x.report('flatten') { arr.map { |x| x << 1001 }.flatten(1) }
x.report('flat_map') { arr.flat_map { |x| x << 1001 } }
end
# test: $ ruby flat_map.rb
# user system total real
# flatten 0.010000 0.000000 0.010000 ( 0.024426)
# flat_map 0.000000 0.000000 0.000000 ( 0.001466)
# test: $ ruby flat_map.rb
# user system total real
# flatten 0.010000 0.000000 0.010000 ( 0.031431)
# flat_map 0.010000 0.000000 0.010000 ( 0.001546)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment