Skip to content

Instantly share code, notes, and snippets.

@igrep
Created March 7, 2011 03:15
Show Gist options
  • Save igrep/858006 to your computer and use it in GitHub Desktop.
Save igrep/858006 to your computer and use it in GitHub Desktop.
Measure efficiency of several methods of string concatenation.
user system total real
Array#push and join 0.360000 0.040000 0.400000 ( 0.398396)
String#concat 1 0.240000 0.030000 0.270000 ( 0.267289)
String#concat 2 0.260000 0.040000 0.300000 ( 0.297610)
Array#join with a const 0.090000 0.030000 0.120000 ( 0.121947)
String#concat with const 0.100000 0.030000 0.130000 ( 0.134064)
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
$VERBOSE = true
=begin
Measure efficiency of several methods of string concatenation.
=end
require 'benchmark'
STR_TO_ADD = ["a", "b"].join("\t") + "\n"
NUM_TRIAL = 100000
Benchmark.bm( 24 ){|bm|
bm.report( 'Array#push and join' ){
a = []
NUM_TRIAL.times do
a << (["a", "b"].join("\t"))
end
s = a.join("\n")
s << "\n"
}
bm.report( 'String#concat 1' ){
s = ""
NUM_TRIAL.times do
s << "a" << "\t" << "b" << "\n"
end
}
bm.report( 'String#concat 2' ){
s = ""
NUM_TRIAL.times do
s << (["a", "b"].join("\t"))
end
}
bm.report( 'Array#join with a const' ){
a = []
NUM_TRIAL.times do
a << STR_TO_ADD
end
s = a.join ''
}
bm.report( 'String#concat with const' ){
s = ""
NUM_TRIAL.times do
s << STR_TO_ADD
end
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment