BigText 如何在不把 10 GB 檔案載入記憶體的情況下執行全部取代
Replace All on a 10 GB file without loading it
BigText 的 Replace All 以 50,000 次匹配為界,採用可復原批次編輯或串流改寫,毋須把整個檔案載入記憶體。在 10 GB 日誌中完成 22,189,930 次替換,耗時 16.8–28.9 秒,峯值私有記憶體為 46.5–62.5 MB。
Drafted with Claude (Anthropic) from BigText's code, notes and benchmark reports. I checked every number and code excerpt against the repository before publishing.
In an ordinary text editor, Replace All is a small loop. The file is in memory, you search it, you build the new text, and you push the old one onto the undo stack. For a 10 GB log the same loop needs at least the file, the result and the undo history in RAM at once: tens of gigabytes for a single click.
BigText is a free, open-source editor for huge text and log files (Windows, Linux, macOS). It never loads a file into memory, so it can't take the easy loop. This article walks through how its Replace All works instead, what it measures at on a 10 GB file, what a pre-1.0 audit of that code found, and how a contributor's pull requests made the undoable path more than a hundred times faster this week.
Two paths, one threshold
Most replacements are small: rename a variable, fix a typo across a few hundred lines. Those should be instant and undoable like any other edit. Only the rare huge ones need different treatment. BigText first collects matches, and gives up as soon as there are too many:
pub enum Collected {
/// Few enough matches: apply as piece-table edits (undoable).
Edits(Vec<(Range<u64>, Vec<u8>)>),
/// More than `threshold` matches: use the streaming path.
TooMany,
Cancelled,
}
let mut exp = Expander::new(tpl, m);
let end = search::search_forward(buf, m, range, cancel, progress, |s, e| {
if edits.len() >= threshold {
too_many = true;
return false;
}
let mut rep = Vec::new();
exp.expand_into(buf, s, e, &mut rep);
edits.push((s..e, rep));
true
});
The threshold is 50,000 matches. Below it, the edits become one batch in the document's piece table: the original file is never touched, the replacements live in a small "add" buffer, and a single Ctrl+Z puts everything back. Above it, the editor asks before it rewrites the file on disk, because undo won't be available for that.
The undoable path, rebuilt this week
A piece table describes the document as a list of pieces: "bytes 0–812 of the file, then 9 bytes of the add buffer, then bytes 815–… of the file". Each replacement splits a piece, so a Replace All just under the threshold leaves about 100,000 pieces.
Until this week, BigText stored them as one array plus two prefix-sum arrays. Both arrays were rebuilt on every edit, so each keystroke cost O(pieces). Worse, while a background search held a snapshot of the document, the first edit copied the whole piece list and the whole add buffer. After a 100 MB paste, every key typed during a search copied 100 MB.
Jahongir Qurbonov found this while reviewing the core
paths, and sent a series of pull requests:
-
#14:
- pieces now sit in leaves of at most 512, each behind an
Arcwith its own byte and newline totals, under a top-level list with prefix sums; - an edit copies one leaf;
- the add buffer became append-only chunks, so a snapshot never forces more than 64 KB of old bytes to be copied.
- pieces now sit in leaves of at most 512, each behind an
- #16: the worker that collects the matches also builds the finished tree, so the UI thread only swaps it in:
pub fn apply_batch(&mut self, batch: Batch) -> Swap {
debug_assert_eq!(
self.add.len(),
batch.base,
"batch built on another add buffer"
);
// All of the batch's bytes go in as one text, so its pieces stay inside one chunk.
self.add.push_owned(batch.add);
let swap = Swap(SwapKind::Whole {
before: self.pieces.clone(),
after: batch.tree,
});
self.apply(&swap, true);
swap
}
Undo keeps the old and new trees, so undoing a whole Replace All is O(1) too.
Measured with the project's edit benchmark (release build, 2 runs; "before" is main with only the benchmark added):
| before | after | |
|---|---|---|
| Build the batch on the worker, 100k pieces | 626 ms | 4.5–4.6 ms |
| Build the batch on the worker, 1M pieces | 6.2–6.3 s | 48 ms |
| Apply it on the UI thread, 1M pieces | 15.3–16.9 ms | 0.002 ms |
| One keystroke, 100k pieces | 480–485 µs | 1.8–1.9 µs |
| One keystroke, 100k pieces, a worker holding a snapshot | 2.6 ms | 7.6–7.9 µs |
| One keystroke after a 100 MB paste, a worker holding a snapshot | 49–56 ms | 1.1–1.4 µs |
Before the merge, the combined change passed the unit tests, the compatibility tests for recovery journals written by every earlier release, and the GUI self-test (255 of 255). I also ran the stress test that checks random edits against a model with 300 random seeds instead of its fixed one. Every text, line count, undo and snapshot check passed.
The streaming path
The large path writes the whole document to a new file, front to back, in one pass. Bytes between two matches are copied, each match is replaced by its expansion, and nothing is kept in memory beyond the current window:
// Copies [from, to) to `out`, straight from the search window when it holds those bytes.
let mut copy = |from: u64,
to: u64,
hay: &[u8],
base: u64,
out: &mut W,
stats: &mut ReplaceStats|
-> io::Result<()> {
if from >= to {
return Ok(());
}
stats.bytes_out += to - from;
if from >= base && to <= base + hay.len() as u64 {
return out.write_all(&hay[(from - base) as usize..(to - base) as usize]);
}
const STEP: u64 = 4 * 1024 * 1024;
let mut p = from;
while p < to {
let e = (p + STEP).min(to);
let n = buf
.read_to(p..e, &mut scratch)
.ok_or_else(|| io::Error::other("could not read the document"))?;
out.write_all(&scratch[..n])?;
p = e;
}
Ok(())
};
The common case is the first branch: the search already read those bytes into its window, so they're written straight from there without a second read. Only a gap longer than the window falls back to reading in 4 MB steps.
The search itself goes through the file in 16 MB windows. A literal pattern uses memchr's memmem, and anything else uses regex-automata. Windows overlap by 1 MB for regular expressions, so a match that crosses a window edge is still found whole.
Templates
In regular-expression mode the replacement can refer to the match with $1 and ${name}, and \n and \t stand for a line break and a tab (on the command line, only with -E). Turning user_id=(\d+) into user=$1 across a log works the same at 10 KB and at 10 GB, because the expansion only ever sees one match.
The expansion used to allocate for every match: it encoded the replacement again, and for $ templates it made new capture slots and copied the match. With 22 million matches that adds up. The same contributor's #15 adds an Expander made once per Replace All. A replacement without $ is encoded once:
let fixed = (!tpl.interpolate).then(|| codec.encode(&tpl.text));
Templates with $ keep their capture slots and buffers from one match to the next. On a 1 GB log, with the output sent to /dev/null so only the CPU counts (3 runs each):
bigtext-cli replace |
before | after |
|---|---|---|
timeout → TIMEOUT!
|
0.48–0.49 s | 0.43–0.55 s |
-E 'id=(\d+)' 'ID[$1]' |
3.01–3.04 s | 2.01–2.02 s |
The output is byte for byte the same.
Saving without risking the original
The new file goes to a temporary name in the same folder. When it's complete, it's flushed with fsync and swapped in atomically: ReplaceFileW on Windows (which keeps the original's attributes and permissions), rename on Linux and macOS. If you cancel, run out of disk space or lose power halfway, the original file is untouched. A cancel or an error also removes the temporary file.
The same code runs without a window:
bigtext-cli replace -E 'user_id=(\d+)' 'user=$1' app.log --in-place --bak
What it measures at
The 10 GB numbers come from the project's benchmark run of 23 November 2026 (BigText 0.12.0, Windows 11, Intel Core Ultra 9 285, NVMe SSD, files in the OS cache). The test file is generated with a fixed seed, so anyone can make the same one. The method and raw reports are in BENCHMARKS.md.
The before/after tables in this article were measured on the same PC on 24 November 2026, with release builds of main before and after the pull requests. Those changes are on main and ship in the next release. They don't change the streaming path's numbers below, which are set by the drive.
10 GB log, timeout → TIMEOUT!
|
3 runs |
|---|---|
| Replacements | 22,189,930 |
Time, including fsync
|
16.8–28.9 s (354–611 MB/s) |
| Peak private memory | 46.5–62.5 MB |
The time is set by the drive, not by the editor: writing the same 10 GB with dd … conv=fsync straight afterwards took 14.7 s and 31.7 s. The drive was 81 % full and had just written 64 GB of test files. The number that depends on BigText is the memory: under 63 MB to rewrite 10 GB.
On GitHub's shared runners (3–4 cores) a 1 GB file with 2.2 million replacements took 0.8–1.7 s on macOS arm64, 3.6–4.0 s on Linux and 4.4–6.2 s on Windows. Those numbers vary a lot between runs and don't represent a real PC.
BENCHMARKS.md now compares opening 1 GB and 10 GB files with klogg, Notepad++ and VS Code on this PC, but not Replace All. A fair comparison needs the same machine, files and cache state for each editor, so I make no claims about other editors' Replace All.
What an audit found
Before calling the command-line tools and file formats stable for 1.0, I had the code audited for bugs that could lose data or crash. Three of the findings were in the search that Replace
All runs on:
-
Byte order marks. A file saved as "CSV UTF-8" by Excel starts with the bytes
EF BB BF. The search started at offset 0, so^matched before the mark. Replacing^with>wrote the text in front of it, and^id,never matched the header line. Matches now start after the mark, and the mark isn't search context either. - UTF-16 files with an odd number of bytes, such as a truncated log. The window end was rounded down to a whole code unit and never reached the file's end, so the search looped forever.
-
Selections that end at the start of a line. With "in selection" on,
^also matched at the selection's end, so the line after it changed too.
All three are fixed in 0.13.0, released on 24 November.
Reviewing a pull request that searches windows in parallel turned up one more, older bug. In a UTF-16 file, a regex match longer than 1 MB that ran past the end of a window was searched again with a longer span to find its real end. That second search accepted no start position at all: the accepted range was [s, s + 1), and rounding it down to whole 2-byte code units left it empty. So the match was dropped and found again one character later, and Replace All left its first character unchanged. The fix accepts one whole code unit. It is on main with a test and ships in the next release.
One limitation remains and is documented: a regular-expression match longer than 1 MB that needs text after it to match at all, like "[^"]*" around a 2 MB value, can be missed where it crosses a 16 MB window edge.
Also merged: indexing and search on several threads
The same series brought more changes that Replace All benefits from, because it runs on the same search:
- #11: newlines are counted 16 bytes at a time with SSE2 (NEON on ARM).
- #12: a large local file is indexed on up to 8 threads, published in file order.
- #13: Find All, filters and the command-line search read and search 16 MB windows on up to 4 threads, with the same matches in the same order.
The review of the threaded versions asked for one rule: a worker that fails to start or panics must not hang the job. Network drives and spinning disks keep a single reader, and BIGTEXT_INDEX_THREADS and BIGTEXT_SEARCH_THREADS turn the threads off.
On this PC, v0.13.0 against main (3 interleaved runs, files in the OS cache):
| v0.13.0 | main |
|
|---|---|---|
| Indexing a 10 GB file | 2.55–2.59 GiB/s | 4.94–4.99 GiB/s |
| Case-insensitive search, 10 GB | 2.50–2.68 GiB/s | 4.27–4.30 GiB/s |
| Regex search in a UTF-16 file | 0.60–0.61 GiB/s | 1.56–1.60 GiB/s |
Match and line counts were identical in every run. The gain is smaller than on the contributor's Linux machine, most likely because on Windows reads of one file go through one synchronous handle and queue up, so only the counting and the searching run in parallel.
What it doesn't do
- The streaming path has no undo. The result is a new file (or the saved document), and the editor asks before it starts.
- A single match is capped at 256 MB.
- Macros and plugins don't exist. This is a tool for big files, not an IDE.
Links
- Source and downloads: https://github.com/Erkinbek/bigtext
- Benchmarks and how to repeat them: https://github.com/Erkinbek/bigtext/blob/main/BENCHMARKS.md
- Known limitations: https://github.com/Erkinbek/bigtext/blob/main/FEATURES.md#known-limitations
- The first article, about opening a 50 GB file: https://dev.to/erkinpardayev/opening-a-50-gb-text-file-without-reading-it-13dk
A note on this article: like most of BigText's code, it was written with Claude, from the project's notes and measurements. I checked it before publishing, and the replies in the comments are mine.
來源:DEV Community · dev.to