Skip to content

Commit 2555500

Browse files
authored
[perf] Improve string encoding performance by ~50%
Entity encoding is a large portion of time spent, since we encode all attribute values and text nodes. This switches encoding from multiple regular expressions to a linear forward scan.
1 parent 13b68cf commit 2555500

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/util.js

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,25 @@ export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine
33

44
const ENCODED_ENTITIES = /[&<>"]/;
55

6-
export function encodeEntities(input) {
7-
const s = String(input);
8-
if (!ENCODED_ENTITIES.test(s)) {
9-
return s;
6+
export function encodeEntities(str) {
7+
if (ENCODED_ENTITIES.test(s) === false) return s;
8+
let start = 0,
9+
i = 0,
10+
out = '',
11+
ch = '';
12+
for (; i<str.length; i++) {
13+
switch(str.charCodeAt(i)) {
14+
case 60: ch = '&lt;'; break;
15+
case 62: ch = '&gt;'; break;
16+
case 34: ch = '&quot;'; break;
17+
case 38: ch = '&amp;'; break;
18+
default: continue;
19+
}
20+
if (i > start) out += str.slice(start, i);
21+
out += ch;
22+
start = i + 1;
1023
}
11-
return s
12-
.replace(/&/g, '&amp;')
13-
.replace(/</g, '&lt;')
14-
.replace(/>/g, '&gt;')
15-
.replace(/"/g, '&quot;');
24+
return out + str.slice(start, i);
1625
}
1726

1827
export let indent = (s, char) =>

0 commit comments

Comments
 (0)