Created
November 13, 2012 18:13
-
-
Save rentalcustard/4067400 to your computer and use it in GitHub Desktop.
inject vs plus
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 | |
private | |
def mapped_vals | |
(1..1_000_000).map do |i| | |
i * i * i * i | |
end | |
end | |
end | |
Benchmark.bmbm do |bm| | |
bm.report("with inject") { PerfTest.new.with_inject([1, 2, 3, 4, 5]) } | |
bm.report("with plus") { PerfTest.new.with_plus([1, 2, 3, 4, 5]) } | |
bm.report("with each") { PerfTest.new.with_each([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
Ξ code/doodles → ruby inject_vs_plus.rb | |
Rehearsal ----------------------------------------------- | |
with inject 1.330000 0.040000 1.370000 ( 1.514304) | |
with plus 0.900000 0.010000 0.910000 ( 0.906701) | |
with each 1.260000 0.030000 1.290000 ( 1.529601) | |
-------------------------------------- total: 3.570000sec | |
user system total real | |
with inject 1.080000 0.010000 1.090000 ( 1.323706) | |
with plus 0.890000 0.010000 0.900000 ( 0.899643) | |
with each 1.450000 0.030000 1.480000 ( 1.961771) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment