Preact: Unnecessary DOM updates compared to React.js [2]

Created on 7 Jun 2017  路  5Comments  路  Source: preactjs/preact

I'm not sure this is the same as issue #690, but at least you can check the diffs more easily online.

Also, I just started on React and Preact yesterday, so I may be missing something.

With Preact, collapsing the first section seems to change most nodes:

https://codesandbox.io/s/L82zkGvj

That doesn't seem to happen with React:

https://codesandbox.io/s/vgyv9OmoL

Is there something missing in the Preact code or in my understanding? I'd love to get a proper lightweight Virtual DOM implementation to use in our application. So, thanks for your effort on achieving such goal :)

Most helpful comment

All 5 comments

Not sure what's causing the change, but I wouldn't rule it might be the same as #690.

dio.js is also doing fine with this task: https://jsfiddle.net/dcp42zs7/

@developit I believe the issue is here

https://github.com/developit/preact/blob/master/src/vdom/diff.js#L231

In the code there is a lookahead of 1 item to decide whether to insert the new node or to remove the old node. In the above example, there were 9 items removed (Field 101 to Field 109 ) so a 1 lookahead isn't enough to detect the removal. Instead of removing the 9 items preact is actually reinserting all the other nodes before Field 101 and then only removing the 9 fields.

Instead of a 1 lookahead, I would suggest doing 2 quick preliminary by-position comparaisons (one from the start and one from the end) to trim common prefixes and suffixes from the old and the new sequences.

This will avoid building a keymap prematurely in most of the cases (since most of the time changes are simple/continuous insertions or deletions). If after the trimming the new sequence is empty (like in the example above) then all what is left is to remove the remaining old elements. Conversely, if after the trimming the old sequence is empty then all what is left is to insert the remaining new elements.

Looking at the sources I think preact could also benefit from other preoptimizations. I find that those described here (https://neil.fraser.name/writing/diff/) apply very well to the virtual dom problem (Possible JS implementation). Also technics used by libs like Snabbdom or Inferno could be very effective

I can't reproduce the issue in the code that's in master anymore. Only the dom nodes that need to be updated are updated :tada:

Was this page helpful?
0 / 5 - 0 ratings