Skip to content

Instantly share code, notes, and snippets.

@kiichi
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save kiichi/554fb16cc231f014af16 to your computer and use it in GitHub Desktop.

Select an option

Save kiichi/554fb16cc231f014af16 to your computer and use it in GitHub Desktop.
##How to tune up javascript
Your app is slow? Try this below.
1. Use Chrome Prifle
1. Run the profiler first
1. Build a hypothsis
1. Apply change
1. 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()
```{javascript}
// 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.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.
```{javascript}
$(":checkbox")
change this to
$("input[type=checkbox]")
```
###Convert .each to raw for statement
I know this is not high impact but try.
```{javascript}
$("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.
```{javascript}
var elems = $("something");
elems.find("something2")
change this to
$(elems, "something2")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment