Transfer Tree to web worker

Hello,

i do some heavy processing on the syntax tree, that I get from the current state of the editor. I would really appreciate if I could transfer the syntax tree to a web worker to do the processing in another thread. Unfortunately I cannot stringify the tree because of circular properties such as “parent” and “tree”.

I only need very few properties of the nodes (“from”, “to”, “name” and “nextSibling”) so I tried to write my own function a ka

function serializeNode(node){
  if(!node){
    return null;
  }
  var t={};
  t.from=node.from;
  t.to=node.to;
  t.firstChild=serializeNode(node.firstChild);
  t.name=node.name;
  t.nextSibling=serializeNode(node.nextSibling);
  return t;
}

Unfortunately this function is slower than the whole processing on the tree…

Is there any possibility to pass a Tree object to a web worker in a decent amount of time?

The tree itself (Tree and TreeBuffer types) is entirely non-circular. But yes, just calling JSON.stringify on it will enter getters like topNode and not work.

Syntax trees can be huge (if the document is big) and heavily use structure sharing on updates (large part of the data structure for the old tree become part of the new tree). As such, serializing them in one go is unlikely to perform well, and indeed will often be slower than just processing them.

If you really want to go down this way you could look into a system that uses WeakMaps to notice substructures it already serialized, and somehow encodes those in a way that allows the other side to reuse its existing value, but probably you’re going to have a better time just doing the work in the main thread.