Javascript string concatenation performance
I was recently profiling some javascript code and began to suspect that the Microsoft Ajax.Net type extension String.format was causing some quite noticeable performance issue so I decided to run some tests to get to the bottom of it. The results were quite surprising.
Test 1 was normal string concatenation:
tf.AddTest(“StringConcat”, function(test){
test.Expects(1);
var start = new Date();
for(var j=0; j<10000; j++){
var str = “hello” + 1 + “hello” + 2 + “hello” + 3 + “hello” + 4 + “hello” + 5;
}
var end = new Date();
alert(end.getTime()-start.getTime());
test.Pass();
});
Test 2 was using the MS type extension:
tf.AddTest(“StringFormat”, function(test){
test.Expects(1);
var start = new Date();
for(var j=0; j<10000; j++){
var str = String.format(“hello{0}hello{1}hello{2}hello{3}hello{4}”, 1,2,3,4,5);
}
var end = new Date();
alert(end.getTime()-start.getTime());
test.Pass();
});
Test 3 was using a home made imitation of the MS type extension using regular expressions to fill in the blanks in the tokenised string:
tf.AddTest(“HomemadeFormat”, function(test){
test.Expects(1);
var start = new Date();
for(var j=0; j<10000; j++){
var str = format(“hello{0}hello{1}hello{2}hello{3}hello{4}”, 1,2,3,4,5);
}
var end = new Date();
alert(end.getTime()-start.getTime());
test.Pass();
});
where format is just a local function (which could easily be attached to the String prototype) defined as follows:
var format = function(tokenised) {
var args = arguments;
return tokenised.replace(/{[0-9]+}/g, function(matched) {
return args[parseInt(matched.replace(/[{}]/g, “”))+1];
});
}
Results for IE 7:
Test 1 : 328 milliseconds
Test 2 : 18626 milliseconds
Test 3 : 860 milliseconds
Results for Firefox 3.0.7:
Test 1 : 1 milliseconds
Test 2 : 6697 milliseconds
Test 3 : 431 milliseconds
Results for Google Chrome:
Test 1 : 8 milliseconds
Test 2 : 1958 milliseconds
Test 3 : 263 milliseconds
So, this is not particularly scientific and doing string concatenation in tight loops is not very realistic etc etc but a few things are pretty clear here. Firstly, simple string concatenation is by far the best approach. Secondly, IE performs a lot worse than the others with any approach. And thirdly, MS Ajax String.Format is a great deal worse than the homemade equivalent. Makes me wander what the other MS Ajax.Net script extensions are like …
leave a comment