Skip to content

Commit

Permalink
loader: speed up line length calc used by moduleProvider
Browse files Browse the repository at this point in the history
When using a loader, for say TypeScript, the esm loader invokes the
`lineLengths` function via `maybeCacheSourceMap` when sourcemaps are
enabled. Therefore, `lineLengths` ends up getting called quite often
when running large servers written in TypeScript for example. Making
`lineLengths` faster should therefore speed up server startup times
for anyone using a loader with node with sourcemaps enabled.

The change itself is fairly simple and is all about removing creation
of unnecessary memory and iterating the whole source content only once
with the hope of making the function cache friendly.
  • Loading branch information
zeusdeux committed Nov 29, 2023
1 parent 431f32e commit 172138f
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions lib/internal/source_map/source_map_cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,26 @@ function dataFromUrl(sourceURL, sourceMappingURL) {
// from. This allows translation from byte offset V8 coverage reports,
// to line/column offset Source Map V3.
function lineLengths(content) {
// We purposefully keep \r as part of the line-length calculation, in
// cases where there is a \r\n separator, so that this can be taken into
// account in coverage calculations.
return ArrayPrototypeMap(RegExpPrototypeSymbolSplit(/\n|\u2028|\u2029/, content), (line) => {
return line.length;
});
const contentLength = content.length;
const output = [];
let lineLength = 0

Check failure on line 210 in lib/internal/source_map/source_map_cache.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Missing semicolon
for (let i = 0; i < contentLength; i++, lineLength++) {
const codePoint = content.codePointAt(i);

// We purposefully keep \r as part of the line-length calculation, in
// cases where there is a \r\n separator, so that this can be taken into
// account in coverage calculations.
// codepoints for \n, \u2028 and \u2029
if (codePoint === 10 || codePoint === 0x2028 || codePoint === 0x2029) {
output.push(lineLength);
lineLength = -1; // to not count the matched codePoint such as \n character

Check failure on line 220 in lib/internal/source_map/source_map_cache.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Comments should not begin with a lowercase character
}
}
output.push(lineLength);
return output;
}


function sourceMapFromFile(mapURL) {
try {
const fs = require('fs');
Expand Down

0 comments on commit 172138f

Please sign in to comment.