Does using a document fragment really improve performance?

后端 未结 7 1455
臣服心动
臣服心动 2020-11-30 01:57

I\'ve got a doubt regarding performance in JS.

Say, I\'ve got the next code:

var divContainer = document.createElement(\"div\"); divContainer.id=\"co         


        
7条回答
  •  伪装坚强ぢ
    2020-11-30 02:25

    I had the exact same question as the OP, and after reading through all the answers and the comments, it didn't seem like anybody really understood what the OP was asking.

    I took a cue from the test Nicola Peluchetti posted and modified it a bit.

    Instead of appending elements to a

    and then appending to the documentFragment, the fragment test gets the elements appended directly to it (the documentFragment) instead of first to the
    . Also, to avoid any hidden overhead costs, both tests begin by creating both the
    container and the documentFragment, while each test only utilizes one or the other.

    I took the original question to be, basically, is it faster to do a single append of nodes using a

    or a documentFragment as the container?

    Looks like using a

    is faster, at least on Chrome 49.

    http://jsperf.com/document-fragment-test-peluchetti/39

    The only use case I can think of for documentFragment (at the moment) is if it takes less memory (which could be negligible), or if you have a bunch of sibling nodes to append which you don't want to put into a "container" element. The documentFragment is like a wrapper which dissolves leaving only its contents.

提交回复
热议问题