Saw this on https://developers.google.com/speed/articles/optimizing-javascript
Can someone please explain how this is more efficient, i.e., why this avoids temporary string results?
Build up long strings by passing string builders (either an array or a helper class) into functions, to avoid temporary result strings.
For example, assuming
buildMenuItemHtml_needs to build up a string from literals and variables and would use a string builder internally, instead of using:var strBuilder = []; for (var i = 0, length = menuItems.length; i < length; i++) { strBuilder.push(this.buildMenuItemHtml_(menuItems[i])); } var menuHtml = strBuilder.join();Use:
var strBuilder = []; for (var i = 0, length = menuItems.length; i < length; i++) { this.buildMenuItem_(menuItems[i], strBuilder); } var menuHtml = strBuilder.join();
I assumed in the first case buildMenuItemHtml_ returned a string and in the second case buildMenuItemHtml_ pushed a string onto strBuilder.