Skip to content

Instantly share code, notes, and snippets.

@spickermann
Created February 17, 2014 23:12
Show Gist options
  • Save spickermann/9061186 to your computer and use it in GitHub Desktop.
Save spickermann/9061186 to your computer and use it in GitHub Desktop.
def array_unshift
foo = [:foo, :bar, :bar]
foo.unshift(:something)
end
def array_concat
foo = [:something]
foo.concat([:foo, :bar, :bar])
end
require 'benchmark'
n = 10_000_000
Benchmark.bmbm(15) do |x|
x.report("array_unshift:") { n.times do; array_unshift; end }
x.report("array_concat:") { n.times do; array_concat; end }
end
# Rehearsal ---------------------------------------------------
# array_unshift: 2.890000 0.030000 2.920000 ( 2.913567)
# array_concat: 3.380000 0.000000 3.380000 ( 3.384986)
# ------------------------------------------ total: 6.300000sec
# user system total real
# array_unshift: 2.870000 0.020000 2.890000 ( 2.898327)
# array_concat: 3.420000 0.000000 3.420000 ( 3.415004)
@johnsyweb
Copy link

Interesting!

#!/usr/bin/env ruby
# encoding: utf-8

require 'benchmark'

headings = Array(1..25)
rows = [Array(1..25)] * 10_000

Benchmark.bm do |b|
  b.report '#unshift' do
    1000.times do
      r = rows.map(&:to_s)
      r.unshift(headings)
    end
  end

  b.report '#concat' do
    1000.times do
      r = []
      r << headings
      r.concat(rows.map(&:to_s))
    end
  end
end

Yielded

./which_way.rb    
       user     system      total        real
#unshift 63.780000   0.240000  64.020000 ( 72.364274)
#concat 62.340000   0.220000  62.560000 ( 70.409771)

@spickermann
Copy link
Author

Conclusion: It does not really matter...

@johnsyweb
Copy link

👍

@pablolee
Copy link

Very interesting results!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment