JavaScript Tune-Ups

How to tune up javascript

Your app is slow? Try this below.

  1. Use Chrome Prifle
  2. Run the profiler first
  3. Build a hypothsis
  4. Apply change
  5. Judge if it's improve it (or worth to change to take a risk. e.g. drawback in readability)

Remember, this often gives a trade-off between performance and code readability.

This document might contain low-impact / urban myth type of tune up as of 2015. Apply from the highest impact tuneup on top of the list below. Most of tips are related to jQuery.

Too many for-loops?

See if you are calling for-loop inside another loooooops. Remember, .each() statement is also a loop.

If you can take it out from the for-loop, do it before / after of it.

String Concatination

Use array then use arr.join()

// this is slower

var str = "";

str += "fdaljlajf a";

str += "fdaljlajf a";

str += "fdaljlajf a";

str += "fdaljlajf a";

// this is faster

var arr = new Array();

arr.push(str);

arr.push(str);

arr.join('');

Avoid Manipulating DOM after ready state

Look for .append() .insert() .remove() .html() etc... that touches DOM tree. See if you can move them out from the loop

Avoid jQuery Specific selectors.

Do not use something that is not defined W3C / CSS3. jQuery extends it's own selector but it costs more cpu power.

$(":checkbox")

change this to

$("input[type=checkbox]")

Convert .each to raw for statement

I know this is not high impact but try.

$("selector").each()

to

var arr = $("selector");

for (var i=0; i<arr.length; i++){

//...

}

Remove Unused Variables

If you see local variable declared but not used, remove it. It could be low impact, but don't VM think you are going to use it later.

Remove .find() statement

This is not high-impact but worth to try.

If you see .find statement in order to find children of some elements. Try to replae with selector's 2nd argment.

var elems = $("something");

elems.find("something2")

change this to

$(elems, "something2")