Skip to content

Instantly share code, notes, and snippets.

@jsanders
Created March 21, 2012 17:11
Show Gist options
  • Save jsanders/2149629 to your computer and use it in GitHub Desktop.
Save jsanders/2149629 to your computer and use it in GitHub Desktop.
String building benchmark code
require 'benchmark'
TIMES = 100_000
strategies = [
[ 'plusequals', proc { str = ""; TIMES.times { str += 'a' } } ],
[ 'interp', proc { str = ""; TIMES.times { str = "#{str}a" } } ],
[ 'concat', proc { str = ""; TIMES.times { str << "a" } } ],
[ 'arrayjoin', proc { ary = []; TIMES.times { ary << 'a' }; str = ary.join } ] ]
10.times do
Benchmark.bm do | bm |
strategies.sort_by { rand }.each do | strategy |
bm.report(strategy.first) { strategy.last.call }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment