|
| 1 | +# Batch Import |
| 2 | + |
| 3 | +## Performance Differences and Their Causes |
| 4 | + |
| 5 | +When importing multiple updates into a document, using `doc.importBatch(updates)` is significantly faster than importing updates individually. This performance difference stems from how data merging is handled in each approach. |
| 6 | + |
| 7 | +```ts |
| 8 | +import { LoroDoc } from "loro-crdt"; |
| 9 | + |
| 10 | +const doc = new LoroDoc(); |
| 11 | +doc.getText("text").update("Hello"); |
| 12 | +const update1 = doc.export({ mode: "update" }); |
| 13 | +const version = doc.version(); |
| 14 | +doc.getText("text").update("Hello World"); |
| 15 | +const update2 = doc.export({ mode: "update", from: version }); |
| 16 | + |
| 17 | +const newDoc1 = new LoroDoc(); |
| 18 | +newDoc1.importBatch([update1, update2]); // faster |
| 19 | + |
| 20 | +const newDoc2 = new LoroDoc(); |
| 21 | +for (const update of [update1, update2]) { // slower |
| 22 | + newDoc2.import(update); |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +### Key Advantages of Import Batch |
| 27 | + |
| 28 | +#### 1. Single Diff Calculation |
| 29 | + |
| 30 | +The most significant advantage is that import batch performs only one diff calculation. In contrast, each individual import follows these steps: |
| 31 | + |
| 32 | +- Merge remote updates into local history |
| 33 | +- Calculate document state changes from the current version to the merged version |
| 34 | +- Apply the diff to the current document state |
| 35 | + |
| 36 | +This diff calculation has fixed overhead costs that accumulate with each import. But `doc.importBatch(...)` only performs one diff calculation, which is faster than multiple individual diff calculations. |
| 37 | + |
| 38 | +#### 2. Reduced Communication Overhead |
| 39 | + |
| 40 | +Import batch also results in more concise events. Each individual import generates a new event, but `doc.importBatch(...)` generates only a single event that contains all the changes. |
0 commit comments