puma-plugin-statsd
puma-plugin-statsd copied to clipboard
Improve performance using `Array#sum`
The following micro benchmark shows Array#sum is better than Array#map with Array#inject.
require 'benchmark'
array = 4.times.to_a
Benchmark.bm(24) {|x|
x.report('Array#sum') do
100000.times {
array.sum(0, &:itself)
}
end
x.report('Array#map & Array#inject') do
100000.times {
array.map(&:itself).inject(0, &:+)
}
end
}
$ ruby -v
ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [arm64-darwin21]
$ ruby benchmard.rb
user system total real
Array#sum 0.014578 0.000027 0.014605 ( 0.014607)
Array#map & Array#inject 0.040410 0.000191 0.040601 ( 0.040623)
Correct me if I'm wrong, but I believe Array#sum was introduced in ruby 2.4. Puma 5.0 supports ruby 2.2+, and puma 6.0 increases that minimum version to 2.4+.
I'm up for merging this, but would prefer to wait until we depend on puma 6 and can safely assume all users are on ruby 2.4+.
Thanks for your reply, @yob. Okay, I missed that puma supports older Ruby versions. I'm keeping this PR as opened.