-
-
Save dharamgollapudi/6d7ca8e828681b451424f6a3e3ba3e24 to your computer and use it in GitHub Desktop.
Ruby flat_map vs. 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| | |
list = (0..10_000).to_a | |
bm.report "flat_map" do | |
list.flat_map do |x| | |
[x, x * x] | |
end | |
end | |
bm.report "map.flatten" do | |
list.map do |x| | |
[x, x * x] | |
end.flatten | |
end | |
bm.compare! | |
end |
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
tobi@happy ~/github/ruby_playground $ ruby benchmark/flat_map.rb | |
Warming up -------------------------------------- | |
flat_map 95.000 i/100ms | |
map.flatten 42.000 i/100ms | |
Calculating ------------------------------------- | |
flat_map 972.133 (± 5.1%) i/s - 4.845k in 5.002625s | |
map.flatten 423.280 (± 2.4%) i/s - 2.142k in 5.063801s | |
Comparison: | |
flat_map: 972.1 i/s | |
map.flatten: 423.3 i/s - 2.30x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment