Skip to content

Instantly share code, notes, and snippets.

@brow
Created January 4, 2012 22:44
Show Gist options
  • Save brow/1562617 to your computer and use it in GitHub Desktop.
Save brow/1562617 to your computer and use it in GitHub Desktop.
Benchmark concatenating strings with reduce(:+) vs. with join('').
require 'benchmark'
STRING = 'abc'
ITERATIONS = 500000
Benchmark.bm do |bench|
for n in [2,3,4]
n_strings = Array.new(n, STRING)
bench.report("add #{n}") do
ITERATIONS.times do
n_strings.reduce(:+)
end
end
bench.report("join #{n}") do
ITERATIONS.times do
tmp = n_strings.join('')
end
end
puts "\n"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment