Skip to content

Proposal for list diff algorithm #1807

Closed
@livoras

Description

@livoras

According to the for directive's diff algorithm, when vue diffs two arrays like:

oldFrags:  a, b, c ,d, e, f, g, h
newFrags:  b, c, d, e, f, g, h, a

it causes seven manipulations of DOM(the move function is called seven times), but the actual minimal amount is just two (remove a from the first place, and insert it to the last).

Vue's list diff algorithm is actually good at cases like inserting new items or moving items from back to front/middle. But cases that just simply moving a item from front to back/middle, it will cause a lot manipulations.

I didn't mean to make it minimal manipulations like levenshtein distance based algorithm does. But moving items from front to back/middle is quite common, so I think it's worth to optimalize.

Here is the pseudocode:

loop frags:
  if not a reused item
    if currentPrev !== targetPrev
      if removing the targetPrev makes currentPrev === elementAfterTargetPrev
        simply remove targetPrev // the removed element will be moved to the right place in future loop
      else
        move(frag, prevEl)
  else 
    simply insert it

It just needs one more if check.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions