rubocop-performance icon indicating copy to clipboard operation
rubocop-performance copied to clipboard

Cop idea: prefer `<<` over `push`

Open amomchilov opened this issue 1 year ago • 0 comments

a << i is faster than a.push(e). I suspect it's because #push takes *args, and the overhead from that is relatively slower than <<, which takes a single arg.

$ ruby --version
ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [arm64-darwin23]

Warming up --------------------------------------
                push     2.673M i/100ms
                  <<     3.180M i/100ms
Calculating -------------------------------------
                push     26.901M (± 0.7%) i/s -    136.334M in   5.068171s
                  <<     32.351M (± 0.8%) i/s -    162.187M in   5.013725s

Comparison:
                  <<: 32350784.7 i/s
                push: 26901465.1 i/s - 1.20x  slower
benchmark.rb
require "benchmark/ips"

a = []
    
Benchmark.ips do |x|
  x.report("push") do |times|
    i = 0
    a.clear
    while (i += 1) < times
      a.push(i)
    end
  end
  
  x.report("<<") do |times|
    i = 0
    a.clear
    while (i += 1) < times
      a << i
    end
  end
  
  x.compare!
end

amomchilov avatar Jan 10 '24 00:01 amomchilov