I’ve been doing some Javascript work lately where I’m doing a fair amount of string concatenation to build up some HTML, and I was curious to see whether the following syntax made any difference in performance:
string = string + "foo"
… vs:
string += "foo"
So I wrote up a little Javascript function to test this:
function startTrial() {
var resultDiv = document.getElementById("trialResults");
var myString = "";
alert("starting long method test");
var start = new Date();
for (var i=0;i<1000000;i++) {
myString = myString + "a";
}
var end = new Date();
var longMethodTime = end - start;
myString = "";
alert("starting short method test");
start = new Date();
for (var i=0;i<1000000;i++) {
myString += "a";
}
end = new Date();
var shortMethodTime = end - start;
var timeDiff = longMethodTime - shortMethodTime;
var pctFaster = (timeDiff/longMethodTime) * 100;
resultDiv.innerHTML = "Long Method = " + longMethodTime + "; Short Method = " + shortMethodTime + " (" + pctFaster + "% faster)";
}
The results (in ms) were a bit surprising:
IE 6 SP 2 (PC):
method 1 | method 2 |
---|---|
1751 | 1659 |
1751 | 1643 |
1751 | 1643 |
Medication may however not work levitra best price well with those affected by psychological causes. This chemical sends a message to the Divine Being that you want to stay together, or strengthen the bond of energy between you even more. viagra pfizer suisse cute-n-tiny.com Contact us today without prescription viagra if you are having problem in getting full erection but its positive side effects are also the same due to the drugs consisting of the same ingredients. It has helped number of men who were more than seventy-five years old and had lost all levitra without prescription hopes of gaining an erection.
Firefox 2 (Mac)
method 1 | method 2 |
---|---|
1672 | 1696 |
1560 | 1712 |
1519 | 1509 |
Firefox 3 (Mac)
method 1 | method 2 |
---|---|
241 | 249 |
245 | 244 |
251 | 255 |
Safari 3 (Mac)
method 1 | method 2 |
---|---|
602 | 557 |
497 | 608 |
502 | 526 |
Google Chrome:
method 1 | method 2 |
---|---|
440 | 442 |
473 | 497 |
429 | 451 |
These tests were all run on a Mac Pro - the IE and Chrome stats were done using Windows XP running on VMWare Fusion. Note that the performance is consistently better in IE6, but didn't really make a difference in any other browser.
If you're game, please try this for yourself; let me know how it goes for you!