Skip to content

Instantly share code, notes, and snippets.

@marcomd
Last active September 12, 2024 15:35
Show Gist options
  • Save marcomd/840a29fc5bd081c2364344c435b005b4 to your computer and use it in GitHub Desktop.
Save marcomd/840a29fc5bd081c2364344c435b005b4 to your computer and use it in GitHub Desktop.
flat_map + compact VS filter_map + flatten
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, x * x] if x.even? }
bm.report "flat_map + compact" do
list.flat_map(&fn).compact
end
bm.report "filter_map + flatten" do
list.filter_map(&fn).flatten
end
bm.compare!
end
@marcomd
Copy link
Author

marcomd commented Sep 10, 2024

ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]
Warming up --------------------------------------
  flat_map + compact   123.000 i/100ms
filter_map + flatten    85.000 i/100ms
Calculating -------------------------------------
  flat_map + compact      1.240k (± 1.5%) i/s  (806.50 μs/i) -      6.273k in   5.060373s
filter_map + flatten    863.176 (± 2.4%) i/s    (1.16 ms/i) -      4.335k in   5.025297s

Comparison:
  flat_map + compact:     1239.9 i/s
filter_map + flatten:      863.2 i/s - 1.44x  slower

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