Skip to content

Instantly share code, notes, and snippets.

@erik-megarad
Forked from brow/gist:1562617
Created January 5, 2012 01:58
Show Gist options
  • Save erik-megarad/1563290 to your computer and use it in GitHub Desktop.
Save erik-megarad/1563290 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(10) do |bench|
for n in [2,3,4, 5]
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
iteratable_dups = (0...ITERATIONS).map { n_strings.map(&:dup) }
bench.report("append #{n}") do
iteratable_dups.each do |dups|
dups.reduce(:<<)
end
end
puts "\n"
end
end
@brutuscat
Copy link

ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin10.8.0]

add  2       0.280000   0.000000   0.280000 (  0.280966)
join 2       0.390000   0.000000   0.390000 (  0.390578)
append 2     0.340000   0.010000   0.350000 (  0.379686)

add  3       0.590000   0.010000   0.600000 (  0.637222)
join 3       1.130000   0.050000   1.180000 (  1.201451)
append 3     0.350000   0.020000   0.370000 (  0.376768)

add  4       0.480000   0.070000   0.550000 (  0.571988)
join 4       1.190000   0.030000   1.220000 (  1.265706)
append 4     0.420000   0.000000   0.420000 (  0.422308)

add  5       0.630000   0.000000   0.630000 (  0.638082)
join 5       1.520000   0.060000   1.580000 (  1.597781)
append 5     0.530000   0.010000   0.540000 (  0.546513)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment