Coding is an Art

Anoiaque::Ergasterium

18/07/2010

String concatenation benchmark in ruby

What to use for concatenate strings in ruby , "+=" or "<<" or concat() ? Here is a benchmark that can guide if concatenations is in a loop.
def benchmark_string_concatenation n
Benchmark.bm(10) do |x|
x.report("With '+=' :") {string = ""; n.times {|n| string += "e"} }
x.report("With '<<' :") {string = ""; n.times { |n|string << "e"} }
x.report("With #concat :") {string = ""; n.times { |n|string.concat("e")} }
end
end


Results with n = 5000:
              user      system    total     real
With '+='   : 0.010000 0.010000 0.020000 ( 0.022831)
With '<<'   : 0.000000 0.000000 0.000000 ( 0.001734) 
With concat : 0.000000 0.000000 0.000000 (0.001689)


Results with n = 50000:
                user    system    total   real
With '+='   : 0.710000 0.000000 0.710000 ( 0.737932)
With '<<'   : 0.020000 0.000000 0.020000 ( 0.019771)
With concat : 0.020000 0.000000 0.020000 ( 0.019853)

Aucun commentaire:

Enregistrer un commentaire

Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it.
Alan Perlis


The best way to predict the future is to invent it.
Alan Kay


Ne découvre de nouvelles terres que celui qui sait quitter tout rivage.
André gide


Qui ne doute pas acquiert peu
Léonard de Vinci


Our life is frittered away by detail... simplify, simplify.
Henry David Thoreau