Skip to content

Commit d7c4f71

Browse files
domenicjgraham
authored andcommitted
Optimize string formatting
Instead of doing 36 passes through the string, do a single pass. This took up around 2% of the time running a large test (Range-mutations-dataChange.html) in jsdom. Part of jsdom/jsdom#3154.
1 parent c31824e commit d7c4f71

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

Diff for: resources/testharness.js

+10-6
Original file line numberDiff line numberDiff line change
@@ -1330,6 +1330,15 @@
13301330
"0xffff": "uffff",
13311331
};
13321332

1333+
const formatEscapeMap = {
1334+
"\\": "\\\\",
1335+
'"': '\\"'
1336+
};
1337+
for (const p in replacements) {
1338+
formatEscapeMap[String.fromCharCode(p)] = "\\" + replacements[p];
1339+
}
1340+
const formatEscapePattern = new RegExp(`[${Object.keys(formatEscapeMap).map(k => k === "\\" ? "\\\\" : k).join("")}]`, "g");
1341+
13331342
/**
13341343
* Convert a value to a nice, human-readable string
13351344
*
@@ -1380,12 +1389,7 @@
13801389

13811390
switch (typeof val) {
13821391
case "string":
1383-
val = val.replace(/\\/g, "\\\\");
1384-
for (var p in replacements) {
1385-
var replace = "\\" + replacements[p];
1386-
val = val.replace(RegExp(String.fromCharCode(p), "g"), replace);
1387-
}
1388-
return '"' + val.replace(/"/g, '\\"') + '"';
1392+
return '"' + val.replace(formatEscapePattern, match => formatEscapeMap[match]) + '"';
13891393
case "boolean":
13901394
case "undefined":
13911395
return String(val);

0 commit comments

Comments
 (0)