Last active
December 29, 2015 02:29
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PaulSmith:~ paul$ ruby Desktop/bench.rb | |
Method A: 0.16236 | |
Method B: 0.18056 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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