Skip to content

Instantly share code, notes, and snippets.

@protist
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save protist/f153d0465cae3f474081 to your computer and use it in GitHub Desktop.
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.
#!/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
@protist
Copy link
Author

protist commented Sep 11, 2014

             user     system      total        real
pipe     1.060000   0.020000   1.080000 (  1.094002)
inject   1.430000   0.020000   1.450000 (  1.494943)

@protist
Copy link
Author

protist commented Sep 12, 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