我有两个javascript函数做同样的事情:创建一个基于json对象的菜单。
一个函数将所有<ul>
和<li>
元素附加到变量,然后使用方法innerHTML
第二个函数通过createElement("ul")
和appendChild()
方法
所以我想知道哪个功能更快,但我不知道如何在javascript中执行基准测试。
我的第一个函数是buildMenutoString()
,第二个函数是buildMenuDOM()
答案 0 :(得分:1)
我使用这样的东西:
var bench = function(fn, iterations){
var time = 0, i = 0, total;
// start
time = +(new Date);
while(i < iterations){
fn.apply();
i++;
}
total = +(new Date) - time;
console.log("Mean exec time: ", total / iterations, 'ms');
console.log("Sum exec time: ", total, 'ms');
};
var test1 = function(){
$('body').append('<div />');
},
test2 = function(){
div = document.createElement('div');
document.body.appendChild(div);
};
bench(test1, 1000);
bench(test2, 1000);
答案 1 :(得分:1)