Last active
August 29, 2015 14:06
-
-
Save protist/f153d0465cae3f474081 to your computer and use it in GitHub Desktop.
Benchmark to compare techniques for selecting and modifying items in an array, in a single block. Mapping + compact vs. inject.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'benchmark' | |
max = 10_000_000 | |
Benchmark.bmbm do |bm| | |
bm.report('pipe') do | |
a = (1..max).to_a | |
a.map! do|i| | |
i + 10 if i.even? | |
end.compact! | |
a | |
end | |
bm.report('inject') do | |
a = (1..max).to_a | |
a = a.inject([]) do |final, element| | |
element.even? ? final.push(element + 10) : final | |
end | |
a | |
end | |
bm.report('flat_map') do | |
a = (1..max).to_a | |
a = a.flat_map do |i| | |
i.even? ? [i + 10] : [] | |
end | |
a | |
end | |
end |
Author
protist
commented
Sep 11, 2014
user system total real
pipe 1.070000 0.010000 1.080000 ( 1.096463)
inject 1.580000 0.020000 1.600000 ( 1.638321)
flat_map 1.830000 0.020000 1.850000 ( 1.843830)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment