zombocom / puma_worker_killer

Automatically restart Puma cluster workers based on max RAM available
747 stars 77 forks source link

Fix compatibility with ruby version 2.3.X #87

Closed adelnabiullin closed 4 years ago

adelnabiullin commented 4 years ago

See https://github.com/schneems/puma_worker_killer/pull/86#issuecomment-643812839

Currently tests are not passing against ruby version 2.3.8 because Enumerable#sum does not exist in that ruby version, it appears starting ruby version 2.4.0

Instead of checking RUBY_VERSION and using sum if it is higher than or equal to 2.4 I decided to replace sum with .inject(:+) because it seems to be the most performant:

require 'benchmark/ips'

workers = {}
1_000.times { |i| workers[i] = rand(1000) }

Benchmark.ips do |x|
  x.report("         sum") { workers.values.sum }
  x.report("  inject(:+)") { workers.values.inject(:+) || 0 }
  x.report(" inject(&:+)") { workers.values.inject(&:+) || 0 }
  x.compare!
end
Warming up --------------------------------------
                 sum    27.656k i/100ms
          inject(:+)    28.784k i/100ms
         inject(&:+)     2.200k i/100ms
Calculating -------------------------------------
                 sum    287.239k (±15.9%) i/s -      1.410M in   5.042619s
          inject(:+)    318.193k (±16.0%) i/s -      1.583M in   5.109662s
         inject(&:+)     21.475k (± 2.7%) i/s -    107.800k in   5.023639s

Comparison:
          inject(:+):   318193.1 i/s
                 sum:   287238.8 i/s - same-ish: difference falls within error
         inject(&:+):    21475.3 i/s - 14.82x  (± 0.00) slower
schneems commented 4 years ago

Thanks!