rubocop / rubocop-performance

An extension of RuboCop focused on code performance checks.
https://docs.rubocop.org/rubocop-performance
MIT License
682 stars 80 forks source link

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

Open amomchilov opened 9 months ago

amomchilov commented 9 months ago

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 ```ruby 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 ```