Skip to content

Cop idea: prefer << over push #431

Open
@amomchilov

Description

@amomchilov

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions