Last active
September 12, 2024 15:40
-
-
Save marcomd/15c8aa02228aef025fb72f2f1298f843 to your computer and use it in GitHub Desktop.
filter_map VS map + compact
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+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 |
Author
marcomd
commented
Sep 12, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment