// js 验证前端代码性能
const comparePerformance = (...fnArr)=>{
// 要验证的核心代码
const coreFn = (fn)=>{
new Promise(()=>{
console.time(fn.name);
// comparePerformance.getParams()
fn&&fn(...comparePerformance.getParams());
console.timeEnd(fn.name);
})
}
// 因为js运行的顺序可能影响性能测试的准确性, 建议取中间区域的测试结果。
var times = 10;
while (times--){
// 顺序
fnArr.forEach((fn)=>{
coreFn(fn)
});
console.log("-------------------------")
}
}
// 需要的构造的参数
comparePerformance.__proto__.getParams = function (){
var arr = [];
let count = 10000
while (count--){
arr.push(Math.floor(Math.random()*10000))
};
return [arr]
}
// 冒泡排序
function bubbleSort(arr) {
for(let i = 0,l=arr.length;i<l-1;i++) {
for(let j = i+1;j<l;j++) {
if(arr[i]>arr[j]) {
let tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
}
return arr;
}
// 希尔排序
function shellSort(arr) {
var len = arr.length,
temp,
gap = 1;
while(gap < len/3) { //动态定义间隔序列
gap = gap*3+1;
}
for (gap; gap > 0; gap = Math.floor(gap/3)) {
for (var i = gap; i < len; i++) {
temp = arr[i];
for (var j = i-gap; j >= 0 && arr[j] > temp; j -= gap) {
arr[j+gap] = arr[j];
}
arr[j+gap] = temp;
}
}
return arr;
}
// 开始测试
comparePerformance(shellSort,bubbleSort)