问题
I have two javascript functions that do same thing: create a menu based on a json object.
One function appends all the <ul>
and <li>
elements to a variable, and then writes the HTML to the document using the method innerHTML
The second function create DOM elements through createElement("ul")
and appendChild()
methods
So I want to know which function is faster, but I do not know how to perform a benchmark test in javascript.
my first function is buildMenutoString()
and the second function is buildMenuDOM()
回答1:
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');
};
Example:
var test1 = function(){
$('body').append('<div />');
},
test2 = function(){
div = document.createElement('div');
document.body.appendChild(div);
};
bench(test1, 1000);
bench(test2, 1000);
回答2:
Have you tried jsperf?
Something like this:
http://jsperf.com/createelement-vs-innerhtml-qweqwe123
来源:https://stackoverflow.com/questions/16349136/how-to-benchmark-javascript-dom-manipulation