[英]How to Benchmark Javascript DOM Manipulation
I have two javascript functions that do same thing: create a menu based on a json object. 我有两个javascript函数做同样的事情:创建一个基于json对象的菜单。
One function appends all the <ul>
and <li>
elements to a variable, and then writes the HTML to the document using the method innerHTML
一个函数将所有
<ul>
和<li>
元素附加到变量,然后使用innerHTML
方法将HTML写入文档
The second function create DOM elements through createElement("ul")
and appendChild()
methods 第二个函数通过
createElement("ul")
和appendChild()
方法创建DOM元素
So I want to know which function is faster, but I do not know how to perform a benchmark test in javascript. 所以我想知道哪个函数更快,但我不知道如何在javascript中执行基准测试。
my first function is buildMenutoString()
and the second function is buildMenuDOM()
我的第一个函数是
buildMenutoString()
,第二个函数是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);
Have you tried jsperf ? 你试过jsperf吗?
Something like this: 像这样的东西:
http://jsperf.com/createelement-vs-innerhtml-qweqwe123 http://jsperf.com/createelement-vs-innerhtml-qweqwe123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.