如何对Javascript DOM操作进行基准测试 [英] How to Benchmark Javascript DOM Manipulation
问题描述
我有两个执行相同功能的javascript函数:基于json对象创建菜单.
I have two javascript functions that do same thing: create a menu based on a json object.
一个函数将所有< ul>
和< li>
元素附加到变量,然后使用方法将HTML写入文档.innerHTML
One function appends all the <ul>
and <li>
elements to a variable, and then writes the HTML to the document using the method innerHTML
第二个函数通过 createElement("ul")
和 appendChild()
方法创建DOM元素
The second function create DOM elements through createElement("ul")
and appendChild()
methods
所以我想知道哪个功能更快,但是我不知道如何在javascript中执行基准测试.
So I want to know which function is faster, but I do not know how to perform a benchmark test in javascript.
我的第一个函数是 buildMenutoString()
,第二个函数是 buildMenuDOM()
my first function is buildMenutoString()
and the second function is buildMenuDOM()
推荐答案
我使用的是这样的内容:
I use something like this:
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);
这篇关于如何对Javascript DOM操作进行基准测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!