Skip to content

Instantly share code, notes, and snippets.

@JunichiIto
Last active May 25, 2017 03:21
Show Gist options
  • Save JunichiIto/21c6bb3f495988121e9c3885a4f53588 to your computer and use it in GitHub Desktop.
Save JunichiIto/21c6bb3f495988121e9c3885a4f53588 to your computer and use it in GitHub Desktop.
require 'benchmark'
def with_sum
(0..9_999_999)
.map { |n| n * 2 }
.select { |n| n % 3 == 0 }
.sum
end
def with_inject
(0..9_999_999)
.map { |n| n * 2 }
.select { |n| n % 3 == 0 }
.inject(:+)
end
Benchmark.bm 10 do |r|
r.report 'with sum' do
with_sum
end
r.report 'with inject' do
with_inject
end
end
# Ruby 2.4.1
# user system total real
# with sum 1.170000 0.030000 1.200000 ( 1.199294)
# with inject 1.190000 0.050000 1.240000 ( 1.243078)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment