js 函數(shù)性能比較方法
在學習js過程中,經(jīng)常會遇到同樣一個功能點 這樣實現(xiàn)也可以,那樣實現(xiàn)也可以。但是哪個方式最優(yōu)呢?自己寫了一個簡短的proferencesCompare 函數(shù)。代碼如下:
/** * 函數(shù)性能比較 * @param fns 要比較的函數(shù)數(shù)組 * @args 每個要比較函數(shù)在執(zhí)行的時候傳入的參數(shù),可以是數(shù)組,或者 被調(diào)用后 返回數(shù)組類型 * @repeatCount 每個函數(shù)重復執(zhí)行的次數(shù),多次執(zhí)行 拉開差距。默認值10000 * * @return [{runTime:執(zhí)行repeatCount次總時間,repeatCount:重復執(zhí)行次數(shù),name:函數(shù)名稱,chrome是函數(shù)名,IE由于不支持funciton.name,所以默認 fn+函數(shù)在fns中index}] * */function proferencesCompare(fns, args, repeatCount) {var tmpArgs, tmpFns;var result = [];var starTime, endTime;var i = 0;var repeatCount = repeatCount || 10000;var isFunction = false;if(fns === undefined) {throw Error(’Must have the compare funciton’);} var typeName = typeof args; //檢測傳入的args是否能夠返回array類型數(shù)據(jù)if(typeName === ’function’) {tmpArgs = args();isFunction = true;} if(typeName === ’number’) {tmpArgs = [];repeatCount = args;} //檢測args 是否為 arrayif(Object.prototype.toString.call(tmpArgs) !== ’[object Array]’) {throw Error(’The test args is must a array or a function which return the array’);} var len = fns.length;for(; i < len; i++) {var fnName = fns[i].name || 'fn' + i;starTime = Date.now();console.time(fnName);for(var j = 0; j < repeatCount; j++) {if(isFunction && (i !== 0 || j !== 0)) {//如果args是函數(shù),并且循環(huán)是第一次進入,則不需要再執(zhí)行一次。前面做args檢測時已經(jīng)執(zhí)行過一次tmpArgs = args();}fns[i].apply(this, tmpArgs);}console.timeEnd(fnName);endTime = Date.now();result.push({ runTime: endTime - starTime, repeatCount: repeatCount, name: fnName });}return result;}
使用例子如下:
var fn1 = function() {var a;return !a;} var fn2 = function() {var a;return a === undefined;} var fn3 = function() {var a;return a == undefined;} var result = proferencesCompare([fn1, fn2, fn3, fn3, fn2, fn1], 1000000000);
這個例子主要比較 對于函數(shù)中 判斷對象是否為undefined 的幾種實現(xiàn)方式的性能比較。
chrome:
結果顯示 其實性能差不多。
下面是其他同學的補充
快速比較代碼執(zhí)行效率的方法
測試效率可以使用Stopwatch :
Stopwatch sw = new Stopwatch();sw.Start();//寫在要執(zhí)行的代碼前面
sw.Stop();//寫在要執(zhí)行的代碼結尾sw.Elapsed//得到代碼執(zhí)行時間
核心函數(shù)
int[] array = { 15,20,10,3,5};Stopwatch sw = new Stopwatch();sw.Start();for (int i = 0; i < array.Length - 1; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[i] > array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } }}sw.Stop();Console.WriteLine(sw.Elapsed);
到此這篇關于js 函數(shù)性能比較方法的文章就介紹到這了,更多相關js 函數(shù)性能內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. idea設置提示不區(qū)分大小寫的方法2. HTTP協(xié)議常用的請求頭和響應頭響應詳解說明(學習)3. IntelliJ IDEA設置默認瀏覽器的方法4. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )5. VMware中如何安裝Ubuntu6. .NET SkiaSharp 生成二維碼驗證碼及指定區(qū)域截取方法實現(xiàn)7. docker容器調(diào)用yum報錯的解決辦法8. IntelliJ IDEA創(chuàng)建web項目的方法9. django創(chuàng)建css文件夾的具體方法10. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容
