Skip to content

Instantly share code, notes, and snippets.

@marcomd
Last active September 12, 2024 15:40
Show Gist options
  • Save marcomd/15c8aa02228aef025fb72f2f1298f843 to your computer and use it in GitHub Desktop.
Save marcomd/15c8aa02228aef025fb72f2f1298f843 to your computer and use it in GitHub Desktop.
filter_map VS map + compact
require 'benchmark/ips'
Benchmark.ips do |bm|
# Create a list with 10_000 elements and some nil values
list = (0..10_000).to_a
fn = ->(x) { x+1 if x.even? }
bm.report "select + map" do
list.select {|x| x.even? }.map {|x| x+1 }
end
bm.report "map + compact" do
list.map(&fn).compact
end
bm.report "filter_map" do
list.filter_map(&fn)
end
bm.compare!
end
@marcomd
Copy link
Author

marcomd commented Sep 12, 2024

ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]
Warming up --------------------------------------
        select + map   216.000 i/100ms
       map + compact   227.000 i/100ms
          filter_map   206.000 i/100ms
Calculating -------------------------------------
        select + map      2.281k (± 3.7%) i/s  (438.45 μs/i) -     11.448k in   5.027572s
       map + compact      2.234k (± 6.6%) i/s  (447.65 μs/i) -     11.123k in   5.005639s
          filter_map      2.035k (± 1.5%) i/s  (491.41 μs/i) -     10.300k in   5.062578s

Comparison:
        select + map:     2280.8 i/s
       map + compact:     2233.9 i/s - same-ish: difference falls within error
          filter_map:     2035.0 i/s - 1.12x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment