Skip to content

Commit 364939f

Browse files
committed
loader: speed up line length calc used by moduleProvider
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.
1 parent 431f32e commit 364939f

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

lib/internal/source_map/source_map_cache.js

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
'use strict';
22

33
const {
4-
ArrayPrototypeMap,
54
JSONParse,
65
ObjectKeys,
76
RegExpPrototypeExec,
8-
RegExpPrototypeSymbolSplit,
97
SafeMap,
8+
StringPrototypeCodePointAt,
109
StringPrototypeSplit,
1110
} = primordials;
1211

@@ -205,14 +204,26 @@ function dataFromUrl(sourceURL, sourceMappingURL) {
205204
// from. This allows translation from byte offset V8 coverage reports,
206205
// to line/column offset Source Map V3.
207206
function lineLengths(content) {
208-
// We purposefully keep \r as part of the line-length calculation, in
209-
// cases where there is a \r\n separator, so that this can be taken into
210-
// account in coverage calculations.
211-
return ArrayPrototypeMap(RegExpPrototypeSymbolSplit(/\n|\u2028|\u2029/, content), (line) => {
212-
return line.length;
213-
});
207+
const contentLength = content.length;
208+
const output = [];
209+
let lineLength = 0;
210+
for (let i = 0; i < contentLength; i++, lineLength++) {
211+
const codePoint = StringPrototypeCodePointAt(content, i);
212+
213+
// We purposefully keep \r as part of the line-length calculation, in
214+
// cases where there is a \r\n separator, so that this can be taken into
215+
// account in coverage calculations.
216+
// codepoints for \n (new line), \u2028 (line separator) and \u2029 (paragraph separator)
217+
if (codePoint === 10 || codePoint === 0x2028 || codePoint === 0x2029) {
218+
output.push(lineLength);
219+
lineLength = -1; // To not count the matched codePoint such as \n character
220+
}
221+
}
222+
output.push(lineLength);
223+
return output;
214224
}
215225

226+
216227
function sourceMapFromFile(mapURL) {
217228
try {
218229
const fs = require('fs');

0 commit comments

Comments
 (0)