七段

          無論怎樣,請讓我先感謝一下國家。

          BlogJava 首頁 新隨筆 聯(lián)系 聚合 管理
            35 Posts :: 2 Stories :: 7 Comments :: 0 Trackbacks
          Efficient JavaScript coding
          1, 盡可能選擇高效的method
          e.g.
          如果沒有必要,可以不用regular expression
          String.indexOf, String.lastIndexOf > String.match, String.search, String.replace

          2, 面對large loop就要斤斤計(jì)較
          2.1 Create once, use repeatedly
          for( var i = 0, oNode; oNode = oElement.childNodes[i]; i++ ) {
          if( oNode.nodeValue.match(/^\s*extra.*free/g) ) {
          //this creates the expression
          //it will be cached and re-used next time through the loop
          }
          }
          for( var i = 0, oNode; oNode = oElement.childNodes[i]; i++ ) {
          if( oNode.nodeValue.match(new RegExp(“^\s*extra.*free”,”g”)) ) {
          //this will always create a new copy of the expression,
          //and is generally much slower than creating static expressions.
          }
          }

          2.2 Referencing element once, use repeatedly
          var _table =$("#tableId")
          for (var index in json) {
          otherFun(_table, json[index]);
          };


          3 eval is evil
          Eval 或者 new Function() 執(zhí)行時(shí),瀏覽器先創(chuàng)建整個(gè)scripting環(huán)境(就像一個(gè)新頁面),導(dǎo)入scope chain中所有變量,執(zhí)行script,gc, 最后導(dǎo)出所有變量到當(dāng)前環(huán)境。(in a word, cost much)另外,js engine還不能對它們進(jìn)行cache優(yōu)化。

          4 less is more
          Less code, short naming
          Only add event listener what you need

          5 do less
          Take a short circuit
          e.g
          var logger=window.console && window.console.dir
          var logger=window.console || {}

          less XHR calling
          e.g. enable cache for the same request

          6 Reduce reflow
          每當(dāng)添加element到document里,browser就會(huì)reflow整個(gè)頁面去計(jì)算如何重新定位和渲染。

          7,cache
          Enable cache for duplicated XHR calling
          Enable cache for js script file, so move out jscript from jsp to js file.

          Reference:
          http://slowjavascript.com/JavaScript_Performance_Rocks_Checklist.pdf


          已有 0 人發(fā)表留言,猛擊->>這里<<-參與討論


          JavaEye推薦




          文章來源:http://sevenduan.javaeye.com/blog/505272
          posted on 2009-10-31 14:49 sevenduan 閱讀(185) 評論(0)  編輯  收藏 所屬分類: JavaScript
          主站蜘蛛池模板: 佛冈县| 五家渠市| 木里| 包头市| 云林县| 嘉祥县| 星座| 阿尔山市| 安岳县| 崇信县| 淮安市| 淮阳县| 贡觉县| 屯昌县| 三门峡市| 屏山县| 廉江市| 南汇区| 昌江| 江孜县| 湖州市| 海晏县| 金阳县| 江西省| 和田县| 汝州市| 高雄县| 海林市| 崇明县| 儋州市| 吴桥县| 利津县| 堆龙德庆县| 从化市| 广南县| 高邑县| 永定县| 阿坝县| 宜宾市| 郁南县| 建始县|