Skip to content

Instantly share code, notes, and snippets.

@rondevera
Created April 24, 2012 18:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondevera/2482368 to your computer and use it in GitHub Desktop.
Save rondevera/2482368 to your computer and use it in GitHub Desktop.
Array push vs concatenation
Benchmark.bmbm do |x|
x.report('<<:') do
arr = []
50_000.times do |i|
arr2 = [i]
arr << arr2
end
end
x.report('+=:') do
arr = []
50_000.times do |i|
arr2 = [i]
arr += arr2
end
end
x.report('concat:') do
arr = []
50_000.times do |i|
arr2 = [i]
arr.concat(arr2)
end
end
end
# Rehearsal -------------------------------------------
# <<: 0.030000 0.000000 0.030000 ( 0.025257)
# +=: 3.260000 2.810000 6.070000 ( 6.084500)
# concat: 1.430000 0.000000 1.430000 ( 1.429430)
# ---------------------------------- total: 7.530000sec
#
# user system total real
# <<: 0.020000 0.000000 0.020000 ( 0.017310)
# +=: 3.190000 2.720000 5.910000 ( 5.910808)
# concat: 1.390000 0.000000 1.390000 ( 1.397712)
# Surprise! Creating 50,000 arrays is slow.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment