-
-
Save andreapavoni/4071291 to your computer and use it in GitHub Desktop.
inject vs plus vs concat
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' | |
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 |
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
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