Skip to content

Instantly share code, notes, and snippets.

@andreapavoni
Forked from rentalcustard/inject_vs_plus.rb
Created November 14, 2012 09:58
Show Gist options
  • Save andreapavoni/4071291 to your computer and use it in GitHub Desktop.
Save andreapavoni/4071291 to your computer and use it in GitHub Desktop.
inject vs plus vs concat
require 'benchmark'
class PerfTest
def with_inject(array)
mapped_vals.inject(array, :<<)
end
def with_plus(array)
array + mapped_vals
end
def with_each(array)
mapped_vals.each {|i| array << i }
array
end
def with_concat(array)
array.concat(mapped_vals)
end
private
def mapped_vals
(1..1_000_000).map do |i|
i * i * i * i
end
end
end
Benchmark.bmbm(10) do |bm|
bm.report("with plus") { PerfTest.new.with_plus([1, 2, 3, 4, 5]) }
bm.report("with concat") { PerfTest.new.with_concat([1, 2, 3, 4, 5]) }
bm.report("with each") { PerfTest.new.with_each([1, 2, 3, 4, 5]) }
bm.report("with inject") { PerfTest.new.with_inject([1, 2, 3, 4, 5]) }
end
Rehearsal -----------------------------------------------
with plus 0.380000 0.020000 0.400000 ( 0.393140)
with concat 0.270000 0.010000 0.280000 ( 0.302586)
with each 0.360000 0.010000 0.370000 ( 0.397857)
with inject 0.380000 0.000000 0.380000 ( 0.421292)
-------------------------------------- total: 1.430000sec
user system total real
with plus 0.300000 0.000000 0.300000 ( 0.307589)
with concat 0.270000 0.000000 0.270000 ( 0.271764)
with each 0.380000 0.000000 0.380000 ( 0.419320)
with inject 0.350000 0.010000 0.360000 ( 0.388192)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment