31⁄2 Perf tips – MD Khan / @mdkhan005 – why performance



31⁄2 Perf tips – MD Khan / @mdkhan005 – why performance

0 0


three-and-a-half-Perf-tips

chicago html5 meetup light talk

On Github khan4019 / three-and-a-half-Perf-tips

31⁄2 Perf tips

MD Khan / @mdkhan005

www.thatjsdude.com

why performance

Array

push vs assign

var a = [];

for (var i = 0; i<10000; i++){
   a.push(i);
}
							
var b = [];

for (var i = 0; i<10000; i++){
   b[i] = i;
}
							
test: push vs assign

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);
								

indexOf Extra Parameter

b.indexOf(669, 500);
								
test: fromIndex

Perf Tip -1

  • a[i]=5 is faster a.push(5)
  • push can insert multiple
  • consider fromIndex if possible

Global Variable

  • Local variable

global scope

var a = 2;
							

local variable

function foo(){

   var b = 21;
}
							
var a = 2; 

function foo(){
   var b = 21;
   return a + b;
}
							

local/function scope

JS scope chain

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

Bubble demo, w3: event flow (image)

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

Debounce & Throttle

Defer

Debounce: Example

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

Final Take Away

Thank You

goo.gl/m4YgDu

MD Khan / @mdkhan005
www.thatjsdude.com
MD Khan / @mdkhan005
www.thatjsdude.com