Is reseting huge document costly?

I’m using Code Mirrors, sometimes for very large files, and I have a question.

If I take that string, and I dispatch a transaction with exactly the same very long string, will this be costly?

const veryLongString = 'something very long here';

dispatch({changes: {from: 0, to: state.doc.length: insert: veryLongString}});
dispatch({changes: {from: 0, to: state.doc.length: insert: veryLongString}}); // if I call it multiple times
dispatch({changes: {from: 0, to: state.doc.length: insert: veryLongString}});
dispatch({changes: {from: 0, to: state.doc.length: insert: veryLongString}});

will this be costly? Or will CodeMirror recognize that nothing changes, and will optimize it somehow?

I’m asking because I’m using Vue, and I must do watch on value, and if value changes I want to change the state of the editor, but sometimes the watch is called even when value doesn’t change, value is the same.

I’m thinking, should I add some kind of checks, if (oldValue != newValue) { dispatch() }, or no need for it, since it will be optimized?

It’s likely going to be costly because the editor has to re-split the lines and re-generate the internal data structure for each line. It will also require re-parsing of the document for syntax highlighting. On top of that, you will also lose some states in relation to the old document because those don’t map very well to the “this entire document has been replaced” change that you’re dispatching. For example, any folding states will be lost.

I’ve dealt with a similar situation previously and the best way here is to write some kind of diffing algorithm to narrow down the changed section to as little as much as possible.

1 Like