js 函数性能比较方法
- 作者: 小龅牙o哔哔哔
- 来源: 51数据库
- 2021-08-16
在学习js过程中,经常会遇到同样一个功能点 这样实现也可以,那样实现也可以。但是哪个方式最优呢?自己写了一个简短的proferencescompare 函数。代码如下:
/**
* 函数性能比较
* @param fns 要比较的函数数组
* @args 每个要比较函数在执行的时候传入的参数,可以是数组,或者 被调用后 返回数组类型
* @repeatcount 每个函数重复执行的次数,多次执行 拉开差距。默认值10000
*
* @return [{runtime:执行repeatcount次总时间,repeatcount:重复执行次数,name:函数名称,chrome是函数名,ie由于不支持funciton.name,所以默认 fn+函数在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类型数据
if(typename === 'function') {
tmpargs = args();
isfunction = true;
}
if(typename === 'number') {
tmpargs = [];
repeatcount = args;
}
//检测args 是否为 array
if(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是函数,并且循环是第一次进入,则不需要再执行一次。前面做args检测时已经执行过一次
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);
这个例子主要比较 对于函数中 判断对象是否为undefined 的几种实现方式的性能比较。
chrome:

结果显示 其实性能差不多。
下面是其他同学的补充
快速比较代码执行效率的方法
测试效率可以使用stopwatch :
stopwatch sw = new stopwatch();
sw.start();//写在要执行的代码前面sw.stop();//写在要执行的代码结尾
sw.elapsed//得到代码执行时间
核心函数
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 函数性能比较方法的文章就介绍到这了,更多相关js 函数性能内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
