perf(codegen): remove bounds check from SourcemapBuilder (#19578)

Follow-on after #19548.

Remove a bounds check from hot loop in `SourcemapBuilder::update_generated_line_and_column` by doing only 1 bounds check to get next 2 bytes, instead of 2 bounds checks for each byte.

This optimization was taken from @cam314's original version of PR #19548.

While reviewing that PR I also thought I'd spied 2 other optimizations, but on reflection, I realized they were better left as is. Add comments to explain why.
This commit is contained in:
overlookmotel committed 2026-02-20 15:00:31 +00:00
1 parent e316694f9f
commit b5fa195233
1 file changed
+13 -3
+13 -3
View File
@@ -254,11 +254,17 @@ impl<'a> SourcemapBuilder<'a> {
continue;
}
LS_OR_PS_FIRST_BYTE => {
let next_byte = output[idx + 1];
let next_next_byte = output[idx + 2];
if !matches!([next_byte, next_next_byte], LS_LAST_2_BYTES | PS_LAST_2_BYTES)
let next_two_bytes = output.get(idx + 1..idx + 3);
if next_two_bytes != Some(&LS_LAST_2_BYTES[..])
&& next_two_bytes != Some(&PS_LAST_2_BYTES[..])
{
last_line_is_ascii = false;
// 3-byte Unicode char that isn't a line break.
// We know it's 3 bytes, so we could do `idx += 3`, but that's more instruction bytes
// than `idx += 1` (`inc` instruction). This branch is extremely rarely taken, and this
// is in a hot loop, so it's better to optimize for the common case.
// The remaining 2 bytes will hit the "Unicode char" branch below on next turns of the loop,
// and they'll be skipped too.
idx += 1;
continue;
}
@@ -268,6 +274,10 @@ impl<'a> SourcemapBuilder<'a> {
_ => {
// Unicode char
last_line_is_ascii = false;
// Note: Only increment `idx` by 1. We don't know how many bytes the char is, and non-ASCII
// chars are rare, so it's not worthwhile adding more instructions to this hot loop to find out.
// The remaining bytes of the char will hit this branch again on next turns of the loop,
// and they'll be skipped too.
idx += 1;
continue;
}