How to Benchmark Javascript DOM Manipulation

六眼飞鱼酱① 提交于 2021-01-29 05:28:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!