rubocop / rubocop-performance

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

Cop idea: prefer `push(...)` over `concat([...])` #434

Closed amomchilov closed 8 months ago

amomchilov commented 8 months ago

I've seen a few place where people are concating array literals, which could have been pushed instead:

- array.concat([1, 2, 3])
+ array.push(1, 2, 3)
$ ruby --version
ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [arm64-darwin23]

Warming up --------------------------------------
                push     2.300M i/100ms
              concat     1.415M i/100ms
Calculating -------------------------------------
                push     23.395M (± 1.5%) i/s -    117.315M in   5.015809s
              concat     14.669M (± 1.5%) i/s -     73.568M in   5.016351s

Comparison:
                push: 23394683.9 i/s
              concat: 14668836.7 i/s - 1.59x  slower
benchmark.rb ```ruby #!/usr/bin/ruby require "benchmark/ips" a = [] Benchmark.ips do |x| x.report("push") do |times| i = 0 a.clear while (i += 1) < times a.push(1, 2, 3) end end x.report("concat") do |times| i = 0 a.clear while (i += 1) < times a.concat([1, 2, 3]) end end x.compare! end ```
vlad-pisanov commented 8 months ago

That's what Style/ConcatArrayLiterals does I believe.

amomchilov commented 8 months ago

@vlad-pisanov 🤦 nice.

I was only searching in rubocop-performance, hahah