Monthly Archives: May 2018

Ruby Array << vs. #push

Was curious which is faster.

Rehearsal ----------------------------------------------
<<           0.099701   0.017560   0.117261 (  0.117427)
push         0.110768   0.007844   0.118612 (  0.118719)
------------------------------------- total: 0.235873sec

                 user     system      total        real
<<           0.063531   0.002646   0.066177 (  0.066220)
push         0.099184   0.004992   0.104176 (  0.104228)

Code:

require 'benchmark'

Benchmark.bmbm(10) do |bm|
  bm.report('<<') do
    a = []
    1000000.times do
      a << 'foo'
    end
  end

  bm.report('push') do
    a = []
    1000000.times do
      a.push 'foo'
    end
  end
end