Skip to content

Instantly share code, notes, and snippets.

@elandesign
Last active December 29, 2015 02:29
Show Gist options
  • Save elandesign/7600821 to your computer and use it in GitHub Desktop.
Save elandesign/7600821 to your computer and use it in GitHub Desktop.
Is it quicker to concatenate individual elements, or construct a new array and add that to the existing one?
require 'benchmark'
repeats = 3
iterations = 1_000_000
def check(repeats, &block)
times = []
repeats.times do
times << Benchmark.realtime(&block)
end
# Return the average
(times.reduce(&:+) / repeats).round(5)
end
result = check(repeats) do
iterations.times do
initial = []
initial << :tom << :dick << :harry
end
end
puts "Method A: #{result}"
result = check(repeats) do
iterations.times do
initial = []
initial += [:tom, :dick, :harry]
end
end
puts "Method B: #{result}"
PaulSmith:~ paul$ ruby Desktop/bench.rb
Method A: 0.16236
Method B: 0.18056
require 'benchmark'
repeats = 3
iterations = 1_000_000
def check(repeats, &block)
times = []
repeats.times do
times << Benchmark.realtime(&block)
end
# Return the average
(times.reduce(&:+) / repeats).round(5)
end
result = check(repeats) do
iterations.times do
initial = []
initial << :tom << :dick << :harry << :huey << :dewey << :louie << :rita << :sue << :bob_too
end
end
puts "Method A: #{result}"
result = check(repeats) do
iterations.times do
initial = []
initial += [:tom, :dick, :harry, :huey, :dewey, :louie, :rita, :sue, :bob_too]
end
end
puts "Method B: #{result}"
PaulSmith:~ paul$ ruby Desktop/bench.rb
Method A: 0.55013
Method B: 0.53659
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment