Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why build strings with helper functions in javascript?

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.

like image 579
Derek Avatar asked Jun 07 '26 17:06

Derek


1 Answers

The important detail is where it says that buildMenuItemHtml_ builds a string from a bunch of different elements. Between the two examples, this happens in two different ways:

Example 1 (builds a string directly):

function buildMenuItemHtml_(data) {
  return ["<li>",data.x,"</li>"].join();
}

or Example 2 (uses a supplied string builder):

function buildMenuItemHtml_(data, strBuilder) {
  strBuilder.push("<li>");
  strBuilder.push(data.x);
  strBuilder.push("</li>");
}

String building is relatively expensive and wasteful since it requires lots of allocations and copies, some of which are temporary and likely to get thrown out. Pushing onto an array is comparatively cheap, and join()ing even a large array ONCE is better than join()ing a whole bunch of small arrays many times.

So rather than having each iteration of the loop build a temporary string (expensive), only to go and build another string (expensive) with those strings, the guideline suggests passing your main string builder directly into the buildMenuItemHtml_ function. By doing this, you don't do any expensive string building until your whole collection of elements is ready -- i.e. once.

like image 60
adpalumbo Avatar answered Jun 10 '26 07:06

adpalumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!