Skip to content

Instantly share code, notes, and snippets.

@dbachet
Created March 2, 2016 18:26
Show Gist options
  • Save dbachet/87a24dde3bb2de5a9137 to your computer and use it in GitHub Desktop.
Save dbachet/87a24dde3bb2de5a9137 to your computer and use it in GitHub Desktop.
Benchmark #flat_map() and flatten.map() in different ruby versions
require 'benchmark/ips'
def flatmap
[[1,2],[3,4]].flat_map {|i| i }
end
def flatten_then_map
[[1,2],[3,4]].flatten.map {|i| i }
end
Benchmark.ips do |x|
x.report('flatmap') { flatmap }
x.report('flatten_then_map') { flatten_then_map }
x.compare!
end
le_daf@macbook-pro-de-damien ~/projects/stackbuilders/haystak/dynamic (feature/hk2475-integrate-styleguide-for-providers●●)$ RBENV_VERSION=2.0.0-p576 ruby bench.rb [2.0.0-p576]
Warming up --------------------------------------
flatmap 36.053k i/100ms
flatten_then_map 22.249k i/100ms
Calculating -------------------------------------
flatmap 548.515k (± 4.7%) i/s - 2.740M
flatten_then_map 311.757k (± 8.1%) i/s - 1.557M
Comparison:
flatmap: 548515.3 i/s
flatten_then_map: 311757.4 i/s - 1.76x slower
le_daf@macbook-pro-de-damien ~/projects/stackbuilders/haystak/dynamic (feature/hk2475-integrate-styleguide-for-providers●●)$ RBENV_VERSION=2.2.3 ruby bench.rb [2.0.0-p576]
Warming up --------------------------------------
flatmap 45.096k i/100ms
flatten_then_map 26.296k i/100ms
Calculating -------------------------------------
flatmap 880.410k (± 3.5%) i/s - 4.419M
flatten_then_map 387.535k (± 3.5%) i/s - 1.946M
Comparison:
flatmap: 880409.6 i/s
flatten_then_map: 387534.5 i/s - 2.27x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment