Push multiple
var a = [1, 2];
a.push(3, 4, 5);
a; // [1, 2, 3, 4, 5]
indexOf
var b = [1, 2, 3, 4, 5, ...];
b.indexOf(669);
Perf Tip -1
a[i]=5 is faster a.push(5)
push can insert multiple
consider fromIndex if possible
global scope
var a = 2;
local variable
function foo(){
var b = 21;
}
var a = 2;
function foo(){
var b = 21;
return a + b;
}
access again and again
var a = 99;
function useGlobal() {
for (j = 0; j < 1000000; j++){
console.log(a);
}
}
var a = 99;
function useLocal() {
var localA = a;
for (var k = 0; k < 1000000; k++){
console.log(localA);
}
}
local vs global variable
Perf Tip -2
Cache out of scope variable
is it hard to
Improve
Performance?
Events
event delegate
<ul id="listToDestroy"> <li><a href="#">first item</a></li> <li><a href="#">second item</a></li> <li><a href="#">third item</a></li> <li><a href="#">forth item</a></li> <li><a href="#">Fifth item</a></li> </ul>
var el = document.getElementById('listToDestroy');
el.addEventListener('click', function (e) {
var elm = e.target.parentNode;
elm.parentNode.removeChild(elm);
e.preventDefault();
});
js perf delegate
event delegate (demo)
add item
Perf Tip -3
Delegate Events
Perf Tip -3.5
Throttle Events
JSPerf.com
popular test
how to create test
3.5 Perf Tips
Array
a[i]=5 is faster a.push(5)
push can insert multiple
consider fromIndex if possible
Cache Global Variable
Bubble up
Throttle/debounce events flow