Skip to content

Instantly share code, notes, and snippets.

@JamesChevalier
Created December 14, 2016 14:59
Show Gist options
  • Save JamesChevalier/1a6fabde0b56c08691aecb48a37c7174 to your computer and use it in GitHub Desktop.
Save JamesChevalier/1a6fabde0b56c08691aecb48a37c7174 to your computer and use it in GitHub Desktop.
Ruby benchmark to compare <<, push, and concat
require 'benchmark'
iterations = 100_000
array_one = []
array_two = []
array_three = []
Benchmark.bmbm do |bm|
bm.report('<<') do
iterations.times do
array_one << [1,2,3,4]
end
array_one.flatten
end
bm.report('push') do
iterations.times do
array_two.push(*[1,2,3,4])
end
end
bm.report('concat') do
iterations.times do
array_three.concat([1,2,3,4])
end
end
end
Rehearsal ------------------------------------------
<< 0.060000 0.000000 0.060000 ( 0.066589)
push 0.040000 0.000000 0.040000 ( 0.043640)
concat 0.020000 0.000000 0.020000 ( 0.024190)
--------------------------------- total: 0.120000sec
user system total real
<< 0.090000 0.000000 0.090000 ( 0.096140)
push 0.030000 0.000000 0.030000 ( 0.025260)
concat 0.030000 0.000000 0.030000 ( 0.023582)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment