.append VS .html VS [removed] performance

前端 未结 7 1666
星月不相逢
星月不相逢 2020-11-28 21:16

This site\'s run a test between the 3 different methods and it seems .html is the fastest, followed by .append. followed by .innerHTML

7条回答
  •  一向
    一向 (楼主)
    2020-11-28 21:42

    That benchmark is worthless. innerHTML is always faster than DOM manipulation.

    jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can.

    jQuery from benchmark

    var html = '';
    for (var i = 0; i < len; i++) {
      html += '
    Test ' + i + '
    '; } $('#list').html(html);

    innerHTML from benchmark

    var list = document.getElementById('list');
    for (var i = 0; i < len; i++) {
      list.innerHTML = list.innerHTML + '
    Test ' + i + '
    '; }

    The test for innerHTML would be a lot faster if it was written like:

    var list = document.getElementById('list');
    var html = '';
    
    for (var i = 0; i < len; i++) {
        html += '
    Test ' + i + '
    '; } list.innerHTML = html;

    http://jsben.ch/#/yDvKH

提交回复
热议问题