javascript 函數嵌套調用的效率測試

來源:互聯網
上載者:User

Javascript中函數嵌套定義給我們開發帶來了很多便利,但是他的效率怎麼樣呢? 我做了一個簡單的測試。

 代碼如下 複製代碼

//test  
 
function func1(a, b) {  
    return (function(a, b){  
        return (function(a, b){return a+b})();  
    })();  
}  
 
function func2(a, b)  
{  
    var nest1 = function(a, b)  
    {  
        var nest11 = function(){  
            return a+b;  
        }  
        return nest11(a+b);  
    }  
    return nest1(a,b);  
}  
 
 
function func3(a, b) {  
    function nest1(a, b){  
        function nest11(a, b){  
            return a+b;  
        }  
        return nest11(a, b);  
    }  
      
    return nest1(a, b);  
}  
 
function nest44(a, b){  
    return a+b;  
}  
 
function nest4(a, b){  
    return nest44(a, b);  
}  
 
function func4(a, b) {  
    return nest4(a, b);  
}  
 
console.time("start1");  
for(var i=0; i<1000000; i++) {  
    func1(1,1);  
}  
console.timeEnd("start1");  
 
console.time("start2");  
for(var i=0; i<1000000; i++) {  
    func2(1,1);  
}  
console.timeEnd("start2");  
 
console.time("start3");  
for(var i=0; i<1000000; i++) {  
    func3(1,1);  
}  
console.timeEnd("start3");  
 
console.time("start4");  
for(var i=0; i<1000000; i++) {  
    func4(1,1);  
}  
console.timeEnd("start4"); 

本代碼用nodejs看執行,得到如下的結果:

# node test2.js

start1: 190ms

start2: 78ms

start3: 58ms

start4: 11ms

如果一個函數被頻繁的調用,將會有一些效率問題了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.