浅谈 Javascript 性能优化

Embed Size (px)

DESCRIPTION

improve javascript performance

Text of 浅谈 Javascript 性能优化

  • JavaScript
    @RainoXuTaobaoUED
    www.rainoxu.com
  • JavaScript

  • 0.1s

    1.0s

    10s

  • What To Do && How To Do?



  • Reflow
    DOM


  • function add(num1, num2){
    return num1 + num2;
    }
    var result = add(5, 10);


  • var a = 1;
    function test(){
    //a
    }
    function test2(){
    var a = 1;
    //a
    }

  • (function(win, S, undefined) {
    ...
    ...
    var doc = win['document'], loc = location,
    EMPTY = '',
    ...
    ...
    })(window, 'KISSY');


  • obj.nameobj.xxx.name
    .
    varobjName = obj.name;
  • KISSY.add('switchable', function(S, undefined) {
    var DOM = S.DOM, Event = S.Event,
    ...
    ...
    });
  • function process(data){
    if (data. count> 0){
    for(vari = 0; i < data.count; i++){
    processData(data.item[i]);
    }
    }
    }
  • function process(data){
    var count = data.count;
    if (count > 0){
    for(vari = 0; i < count ; i++){
    processData(data.item[i]);
    }
    }
    }
  • NodeList
    NodeList

    Array.prototype.slice.call() =>
    => For IE
  • JSArray-LikeArrayKISSYmakeArray()JSArrayYUIDOM
  • NodeListNodeListDOM
  • vardivs = document.getElementsByTagName('DIV');
    //divdivs.length0
    for (varidx = 0; idx < divs.length; idx++){
    document.body.appendChild(
    //
    document.createElement('DIV')
    );
    console.info(divs.length);
    }

  • getElementsByTagName()LiveNodeListDOMNodeList
    document.bodydiv fordiv.length
  • Live NodeListvs Static NodeList
    Live NodeList
  • Live NodeListvs Static NodeList
    Live NodeList
  • Live NodeListvs Static NodeList
    Live NodeListJS
  • DOM
    DOMcontext
    YUI:
    Array getElementsByClassName ( className , tag , root , apply , o , overrides )
    KISSY:
    Array query ( selector, context )
    JS:
    context.getElementsByTagName()
  • DOM

    DocumentFragment
    cloneNode()
    DOMdisplay:none;


  • KISSY Poster
  • KISSY Poster
  • Be Lazy

  • a && b || c



  • DOM

  • Event.on ( target, type, fn, scope )




  • Event.on(container, click, function (ev){
    var target = ev.target();
    switch(target.className){//nodeName
    ...
    ...
    ...
    }
    });

  • if(...){
    }elseif(...){
    }elseif(...){
    }elseif(...){
    }elseif(...){
    }elseif(...){
    }else{
    }
  • if
    if
    switch


  • varfoo = 0;
    if(foo == false){
    ...
    }

  • function recurse(){
    recurse();
    }
    recurse();//


  • Reflow
  • Reflow
    DOM

    className




  • DOM




  • 2/8



  • YAHOOJohnResigNicholasC.Zakas