Last active
September 12, 2024 15:35
-
-
Save marcomd/840a29fc5bd081c2364344c435b005b4 to your computer and use it in GitHub Desktop.
flat_map + compact VS filter_map + flatten
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
marcomd
commented
Sep 10, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment