Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is this still the case with the newer transactional methods like Element.append(), Element.before(), and DocumentFragment?

When I manipulate the DOM I try to create the entire structure in a fragment and the use .append(...) only once.



This:

    element.append([array of Elements]);
is in magnitude of times faster than

    for(const el of [array of Elements])
      element.appendChild(el);
so yes, it helps to improve situation.

But think about updates like this:

   element.patch(<p multiple={n > 1}>There {n > 1? "are": "is"} {n} bottle{n > 1? "s": ""} of beer on the wall</p>);
Here you need to update (or not) as the attribute as text nodes. You need some transactional mutation mechanism.


Oddly enough, this doesn't seem to be accurate: check out https://jsbench.me/02l63eic9j/1.

I also would have sworn up and down that using a DocumentFragment would be loads faster than both, but it doesn't seem to be the case. I wonder why that is.



> this doesn't seem to be accurate

It is pretty accurate here, case #3 is significantly (almost two times) slower than case #1.


Not on my browser (Safari 16.1). Here case #3 is the fastest, over 7% faster than case #1.


Seems like Safari has quite naive element.append(...list) implementation and/or "destructuring to argv" operation is slow there.

I suspect that element.append(...list) is just a

   for(auto arg : args) 
     element.append(arg);
so no transaction there at all - slower version of case #3.

On Windows I am testing it in Edge, Chrome and FF. Edge and Chrome show close numbers (#1 fastest). FF shows #3 is faster - same problem as Safari I think.


I'd be interesting in learning the answer here as well. I've read that documentFragment are faster, but some microbenchmarking on chrome/mac makes me think either the improvements are negligible. Rerunning benchmarks on stackoverflow (https://stackoverflow.com/questions/14203196/does-using-a-do...) (both individually and swapping the order of fragment vs non-fragment tests) nets me ~60ms when rendering 100000 ul in each case.

My naive take on this is that browsers have overall gotten a lot more consistent with the layout-paint-composite loop, and it's not worthwhile to swap out all your appendChild calls with fragments. On the other hand, making sure your all your layout reads (.clientWidth) are batched before the layout writes (appendChild) is much more important (fastdom)

edit: something like documentFragment/append(...children) would help guarantee the layout trashing addressed by fastdom


Fragments are still real dom nodes, and those are heavy.

Unless you getting computed styles in between add/deletions, etc, I don’t think there would be much of a difference.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: