I read this article about javasccript performance on string concatenation and scope variable so I rewrote some of my code the way it was suggested but the recommended way is MUCH slower. I’m testing using Chrome and IE: similar conclusion.
Basically, I have an object that contains strings and I’m loop through each value to generate HTML. The two ways I’m comparing are doing:
var TheHTML = "";
TheHTML = TheHTML + ...;
and the other way is using an array and join
TheHTML[i++] = ....;
I have a fiddle here. The code I’m using looks like this:
var ObjectTest = {};
ObjectTest.Key1 = "The Key 1";
ObjectTest.Key2 = "The Key 2";
ObjectTest.Key3 = "The Key 3";
ObjectTest.Key4 = "The Key 4";
ObjectTest.Key5 = "The Key 5";
function TestSpeed() {
var TheHTML1 = "";
var THeHTML2 = "";
var TheStart1 = new Date().getTime();
for (var TestPerf1 = 0; TestPerf1 < 100000; TestPerf1++) {
TheHTML1 = "";
TheHTML1 = TheHTML1 + '<div style="clear:both">' + ObjectTest.Key1 + '</div>';
TheHTML1 = TheHTML1 + '<div style="clear:both">' + ObjectTest.Key2 + '</div>';
TheHTML1 = TheHTML1 + '<div style="clear:both">' + ObjectTest.Key3 + '</div>';
TheHTML1 = TheHTML1 + '<div style="clear:both">' + ObjectTest.Key4 + '</div>';
TheHTML1 = TheHTML1 + '<div style="clear:both">' + ObjectTest.Key5 + '</div>';
TheHTML1 = TheHTML1 + '<br><br>';
}
document.getElementById('TestOutput1').innerText = new Date().getTime() - TheStart1;
document.getElementById('Output1').innerHTML = TheHTML1;
var TheStart2 = new Date().getTime();
var ObjectTestCopy = ObjectTest;
for (var TestPerf2 = 0; TestPerf2 < 100000; TestPerf2++) {
var Test = [];
var i = 0;
Test[i++] = '<div style="clear:both">' + ObjectTestCopy.Key1 + '</div>';
Test[i++] = '<div style="clear:both">' + ObjectTestCopy.Key2 + '</div>';
Test[i++] = '<div style="clear:both">' + ObjectTestCopy.Key3 + '</div>';
Test[i++] = '<div style="clear:both">' + ObjectTestCopy.Key4 + '</div>';
Test[i++] = '<div style="clear:both">' + ObjectTestCopy.Key5 + '</div>';
Test[i++] = '<br><br>';
TheHTML2 = Test.join("");
}
document.getElementById('TestOutput2').innerText = new Date().getTime() - TheStart2;
document.getElementById('Output2').innerHTML = TheHTML2;
}
window.onload = function () { TestSpeed(); }
Why is the suggested code slower?
It helps if you read the ENTIRE article: