一、統(tǒng)計函數(shù)執(zhí)行次數(shù)
常規(guī)的方法可以使用 console.log 輸出來肉眼計算有多少個輸出
不過在Chrome中內(nèi)置了一個 console.count 方法,可以統(tǒng)計一個字符串輸出的次數(shù)。我們可以利用這個來間接地統(tǒng)計函數(shù)的執(zhí)行次數(shù)
function someFunction() { console.count('some 已經(jīng)執(zhí)行');}function otherFunction() { console.count('other 已經(jīng)執(zhí)行');}someFunction(); // some 已經(jīng)執(zhí)行: 1someFunction(); // some 已經(jīng)執(zhí)行: 2otherFunction(); // other 已經(jīng)執(zhí)行: 1console.count(); // default: 1console.count(); // default: 2不帶參數(shù)則為 default 值,否則將會輸出該字符串的執(zhí)行次數(shù),觀測起來還是挺方便的
當然,除了輸出次數(shù)之外,還想獲取一個純粹的次數(shù)值,可以用裝飾器將函數(shù)包裝一下,內(nèi)部使用對象存儲調用次數(shù)即可
var getFunCallTimes = (function() { // 裝飾器,在當前函數(shù)執(zhí)行前先執(zhí)行另一個函數(shù) function decoratorBefore(fn, beforeFn) { return function() { var ret = beforeFn.apply(this, arguments); // 在前一個函數(shù)中判斷,不需要執(zhí)行當前函數(shù) if (ret !== false) { fn.apply(this, arguments); } }; } // 執(zhí)行次數(shù) var funTimes = {}; // 給fun添加裝飾器,fun執(zhí)行前將進行計數(shù)累加 return function(fun, funName) { // 存儲的key值 funName = funName || fun; // 不重復綁定,有則返回 if (funTimes[funName]) { return funTimes[funName]; } // 綁定 funTimes[funName] = decoratorBefore(fun, function() { // 計數(shù)累加 funTimes[funName].callTimes++; console.log('count', funTimes[funName].callTimes); }); // 定義函數(shù)的值為計數(shù)值(初始化) funTimes[funName].callTimes = 0; return funTimes[funName]; }})();function someFunction() { }function otherFunction() { }someFunction = getFunCallTimes(someFunction, 'someFunction');someFunction(); // count 1someFunction(); // count 2someFunction(); // count 3someFunction(); // count 4console.log(someFunction.callTimes); // 4otherFunction = getFunCallTimes(otherFunction);otherFunction(); // count 1console.log(otherFunction.callTimes); // 1otherFunction(); // count 2console.log(otherFunction.callTimes); // 2二、統(tǒng)計函數(shù)執(zhí)行時間
Chrome中內(nèi)置了 console.time 和 console.timeEnd 來打點計算時間
console.time();for (var i = 0; i < 100000; ++i) {}console.timeEnd(); // default: 1.77197265625ms不傳入?yún)?shù)的話,將以default輸出毫秒值
我們可以封裝一下,傳入函數(shù)名稱,類似上面的做法,使用裝飾器在函數(shù)執(zhí)行前后進行處理
var getFunExecTime = (function() { // 裝飾器,在當前函數(shù)執(zhí)行前先執(zhí)行另一個函數(shù) function decoratorBefore(fn, beforeFn) { return function() { var ret = beforeFn.apply(this, arguments); // 在前一個函數(shù)中判斷,不需要執(zhí)行當前函數(shù) if (ret !== false) { fn.apply(this, arguments); } }; } // 裝飾器,在當前函數(shù)執(zhí)行后執(zhí)行另一個函數(shù) function decoratorAfter(fn, afterFn) { return function() { fn.apply(this, arguments); afterFn.apply(this, arguments); }; } // 執(zhí)行次數(shù) var funTimes = {}; // 給fun添加裝飾器,fun執(zhí)行前后計時 return function(fun, funName) { return decoratorAfter(decoratorBefore(fun, function() { // 執(zhí)行前 console.time(funName); }), function() { // 執(zhí)行后 console.timeEnd(funName); }); }})();
新聞熱點
疑難解答
圖片精選