-
-
Save erik-megarad/1563290 to your computer and use it in GitHub Desktop.
Benchmark concatenating strings with reduce(:+) vs. with join('').
This file contains 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' | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin10.8.0]