RuboCop: Fix offenses for Performance/MethodObjectAsBlock
What does this MR do and why?
This MR fixes offenses for Performance/MethodObjectAsBlock
(part 1 of 2) manually.
How to set up and validate locally
bundle exec rubocop --only Performance/MethodObjectAsBlock --parallel
Benchmark
From https://github.com/fastruby/fast-ruby#normal-way-to-apply-method-vs-method-code
Using &method(...)
is ~2.5x slower than { ... }
.
Click to expand
# frozen_string_literal: true
require "benchmark/ips"
def do_something(n)
4*n + 2
end
def fast
[1, 2, 3].map { |n| do_something(n) }
end
def slow
[1, 2, 3].map(&method(:do_something))
end
Benchmark.ips do |x|
x.report("normal") { fast }
x.report("&method") { slow }
x.compare!
end
Warming up --------------------------------------
normal 397.640k i/100ms
&method 171.679k i/100ms
Calculating -------------------------------------
normal 3.550M (±21.7%) i/s - 17.099M in 5.098570s
&method 1.426M (± 8.5%) i/s - 7.211M in 5.098390s
Comparison:
normal: 3549722.4 i/s
&method: 1425508.8 i/s - 2.49x (± 0.00) slower
MR acceptance checklist
This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.
-
I have evaluated the MR acceptance checklist for this MR.
Edited by Peter Leitzen