巧用局部變數可以有效提升javascript效能,下面有個不錯的樣本,大家可以參考下
javascript中一個標識符所在的位置越深,它的讀寫速度也越慢。因此,函數中讀寫局部變數總是最快的,而讀寫全域變數通常是最慢的。一個好的經驗法則是:如果某個跨範圍的值在函數中被引用一次以上,那麼就把它儲存到局部變數裡。 例如: 代碼如下:<!-- 最佳化前 --> <script type="text/javascript"> function initUI () { var bd = document.body, links = document.getElementByTagName("a"), i=0, len=links.length; while(i < len){ update(links[i++]); } document.getElementById("go-btn").onclick = function(){ start(); } bd.className = "active"; } </script> 該函數引用了三次document,而document是個全域對象。搜尋該變數的過程必須遍曆整個範圍連結,直到最後在全域變數對象中找到。你可以通過以下方法減少對效能的影響:先將全域變數的引用儲存在一個局部變數中,然後使用這個局部變數代替全域變數。 例如: 代碼如下:<!-- 最佳化後 --> <script type="text/javascript"> function initUI () { var doc=document, bd = doc.body, links = doc.getElementByTagName("a"), i=0, len=links.length; while(i < len){ update(links[i++]); } doc.getElementById("go-btn").onclick = function(){ start(); } bd.className = "active"; } </script>