Skip to content

Commit 686ce4e

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 686ce4e

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

lib/internal/source_map/source_map_cache.js

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

33
const {
4-
ArrayPrototypeMap,
54
JSONParse,
65
ObjectKeys,
76
RegExpPrototypeExec,
8-
RegExpPrototypeSymbolSplit,
97
SafeMap,
108
StringPrototypeSplit,
119
} = primordials;
@@ -205,14 +203,26 @@ function dataFromUrl(sourceURL, sourceMappingURL) {
205203
// from. This allows translation from byte offset V8 coverage reports,
206204
// to line/column offset Source Map V3.
207205
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-
});
206+
const contentLength = content.length;
207+
const output = [];
208+
let lineLength = 0;
209+
for (let i = 0; i < contentLength; i++, lineLength++) {
210+
const codePoint = content.codePointAt(i);
211+
212+
// We purposefully keep \r as part of the line-length calculation, in
213+
// cases where there is a \r\n separator, so that this can be taken into
214+
// account in coverage calculations.
215+
// codepoints for \n, \u2028 and \u2029
216+
if (codePoint === 10 || codePoint === 0x2028 || codePoint === 0x2029) {
217+
output.push(lineLength);
218+
lineLength = -1; // To not count the matched codePoint such as \n character
219+
}
220+
}
221+
output.push(lineLength);
222+
return output;
214223
}
215224

225+
216226
function sourceMapFromFile(mapURL) {
217227
try {
218228
const fs = require('fs');

0 commit comments

Comments
 (0)