巧用局部變數提升javascript效能

來源:互聯網
上載者:User

巧用局部變數提升javascript效能

 巧用局部變數可以有效提升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> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.