Which is better: string html generation or jquery DOM element creation?

后端 未结 4 599
逝去的感伤
逝去的感伤 2020-12-05 08:12

Ok, I\'m rewriting some vanilla JS functions in my current project, and I\'m at a point where there\'s a lot of HTML being generated for tooltips etc.

My question is

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 08:36

    I have tested the code Nick Craver has submitted and have found that DOM caching works faster only if the content of the element does not change. If you however alter the string in each iteration of the for loop, the speed dramatically decreases.

    Here's the same code modified (test it on Fiddle: http://jsfiddle.net/Ps5ja/42/)

    console.time('concat');
    var html = "";
    for(var i = 0; i < 500; i++) {
        html += '
    Some More Stuff
    '; html += '
    Some Conditional Content
    '; } var elem = $(html); console.timeEnd('concat'); console.time('DOM'); var parent = $("
    ") for(var j = 0; j < 500; j++) { parent.append($('
    ').append($('', {text :'Some More Stuff'}))); parent.append($('
    ',{ text: 'Some conditionalContent' })); } console.timeEnd('DOM'); console.time('concat caching'); var html = ""; for(var i = 0; i < 10000; i++) html += '
    Some More Stuff
    Some Conditional Content'+i+'
    '; var elem = $(html); console.timeEnd('concat caching'); console.time('concat array.join'); var arr = []; for(i = 0; i < 10000; i++) arr.push('
    Some More Stuff
    Some Conditional Content'+i+'
    '); var elem = $(arr.join('')); console.timeEnd('concat array.join'); console.time('DOM caching - NO modification'); var parent = $("
    ") // here the contained text is unchanged in each iteration for(var j = 0; j <10000; j++) parent.append('
    Some More Stuff
    Some Conditional Content
    '); console.timeEnd('DOM caching - NO modification'); console.time('DOM caching with modification'); var parent = $("
    ") // here the contained text is modified in each iteration // (the value od J is appended to the text) for(var j = 0; j <10000; j++) parent.append('
    Some More Stuff
    Some Conditional Content'+j+'
    '); console.timeEnd('DOM caching with modification');

    The conclusion is that DOM caching works faster only if you plan to replicate the same HTML fragment over and over. If not go with the string concatenation.

    I haven't found any speed benefits in using Array.join method. However I haven't tested that thoroughly (it might be that changes if the number of iterations is bigger).

提交回复
热议问题