Skip to content

Commit 1012e3a

Browse files
authored
pref: rework unesc for a 63+% performance boost (postcss#239)
* In profiling postcss I found that a significant amount of time was being spent in [`unesc`](https://github.com/postcss/postcss-selector-parser/commits/master/src/util/unesc.js), this was due to the expensive regex checks that were being performed on the fly for every selector in the codebase which looked to be performing quite poorly inside of modern node and v8. ![image](https://user-images.githubusercontent.com/883126/114136698-fdd98a80-98bf-11eb-8068-ace4f6f2274d.png) ---- As an experiment and based on some prior experience with this class of slowdown I migrated the implementation to one that performs a scan through the string instead of running a regex replace. By testing this on my local application I instantly saw the work from this function go from > 900 ms to ~100ms. ![image](https://user-images.githubusercontent.com/883126/114136734-0c27a680-98c0-11eb-82ab-f0c9529fd32d.png) This implementation passes all of the existing test cases and aims to mirror the prior implementation's implementation details :) ----- Based on my application I am seeing the major wins come from purgecss dropping my total application build by multiple seconds! 🔥 * Expand unesc handling to correctly handle spec edgecase for lone surrogates and out of bound codepoint values.
1 parent 96a85e3 commit 1012e3a

File tree

3 files changed

+142
-16
lines changed

3 files changed

+142
-16
lines changed

src/__tests__/classes.js

+1
Original file line numberDiff line numberDiff line change
@@ -264,3 +264,4 @@ test('class selector with escaping (36)', '.not-pseudo\\:\\:focus', (t, tree) =>
264264
t.deepEqual(tree.nodes[0].nodes[0].type, 'class');
265265
t.deepEqual(tree.nodes[0].nodes[0].raws.value, 'not-pseudo\\:\\:focus');
266266
});
267+

src/__tests__/util/unesc.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import {test} from '../util/helpers';
2+
3+
test('id selector', '#foo', (t, tree) => {
4+
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo');
5+
});
6+
7+
test('escaped special char', '#w\\+', (t, tree) => {
8+
t.deepEqual(tree.nodes[0].nodes[0].value, 'w+');
9+
});
10+
11+
test('tailing escape', '#foo\\', (t, tree) => {
12+
t.deepEqual(tree.nodes[0].nodes[0].value, 'foo\\');
13+
});
14+
15+
test('double escape', '#wow\\\\k', (t, tree) => {
16+
t.deepEqual(tree.nodes[0].nodes[0].value, 'wow\\k');
17+
});
18+
19+
test('leading numeric', '.\\31 23', (t, tree) => {
20+
t.deepEqual(tree.nodes[0].nodes[0].value, '123');
21+
});
22+
23+
test('emoji', '.\\🐐', (t, tree) => {
24+
t.deepEqual(tree.nodes[0].nodes[0].value, '🐐');
25+
});
26+
27+
// https://www.w3.org/International/questions/qa-escapes#cssescapes
28+
test('hex escape', '.\\E9motion', (t, tree) => {
29+
t.deepEqual(tree.nodes[0].nodes[0].value, 'émotion');
30+
});
31+
32+
test('hex escape with space', '.\\E9 dition', (t, tree) => {
33+
t.deepEqual(tree.nodes[0].nodes[0].value, 'édition');
34+
});
35+
36+
test('hex escape with hex number', '.\\0000E9dition', (t, tree) => {
37+
t.deepEqual(tree.nodes[0].nodes[0].value, 'édition');
38+
});
39+
40+
test('class selector with escaping', '.\\1D306', (t, tree) => {
41+
t.deepEqual(tree.nodes[0].nodes[0].value, '𝌆');
42+
});
43+
44+
test('class selector with escaping with more chars', '.\\1D306k', (t, tree) => {
45+
t.deepEqual(tree.nodes[0].nodes[0].value, '𝌆k');
46+
});
47+
48+
test('class selector with escaping with more chars with whitespace', '.wow\\1D306 k', (t, tree) => {
49+
t.deepEqual(tree.nodes[0].nodes[0].value, 'wow𝌆k');
50+
});
51+
52+
test('handles 0 value hex', '\\0', (t, tree) => {
53+
t.deepEqual(tree.nodes[0].nodes[0].value, String.fromCodePoint(0xFFFD));
54+
});
55+
56+
test('handles lone surrogate value hex', '\\DBFF', (t, tree) => {
57+
t.deepEqual(tree.nodes[0].nodes[0].value, String.fromCodePoint(0xFFFD));
58+
});
59+
60+
test('handles out of bound values', '\\110000', (t, tree) => {
61+
t.deepEqual(tree.nodes[0].nodes[0].value, String.fromCodePoint(0xFFFD));
62+
});

src/util/unesc.js

+79-16
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,82 @@
1-
const whitespace = '[\\x20\\t\\r\\n\\f]';
2-
const unescapeRegExp = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig');
1+
// Many thanks for this post which made this migration much easier.
2+
// https://mathiasbynens.be/notes/css-escapes
3+
4+
/**
5+
*
6+
* @param {string} str
7+
* @returns {[string, number]|undefined}
8+
*/
9+
function gobbleHex (str) {
10+
const lower = str.toLowerCase();
11+
let hex = '';
12+
let spaceTerminated = false;
13+
for (let i = 0; i < 6 && lower[i] !== undefined; i++) {
14+
const code = lower.charCodeAt(i);
15+
// check to see if we are dealing with a valid hex char [a-f|0-9]
16+
const valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57);
17+
// https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
18+
spaceTerminated = code === 32;
19+
if (!valid) {
20+
break;
21+
}
22+
hex += lower[i];
23+
}
24+
25+
if (hex.length === 0) {
26+
return undefined;
27+
}
28+
const codePoint = parseInt(hex, 16);
29+
30+
const isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
31+
// Add special case for
32+
// "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
33+
// https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
34+
if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
35+
return ['\uFFFD', hex.length + (spaceTerminated ? 1 : 0)];
36+
}
37+
38+
return [
39+
String.fromCodePoint(codePoint),
40+
hex.length + (spaceTerminated ? 1 : 0),
41+
];
42+
}
43+
44+
const CONTAINS_ESCAPE = /\\/;
345

446
export default function unesc (str) {
5-
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
6-
const high = '0x' + escaped - 0x10000;
7-
8-
// NaN means non-codepoint
9-
// Workaround erroneous numeric interpretation of +"0x"
10-
// eslint-disable-next-line no-self-compare
11-
return high !== high || escapedWhitespace
12-
? escaped
13-
: high < 0
14-
? // BMP codepoint
15-
String.fromCharCode(high + 0x10000)
16-
: // Supplemental Plane codepoint (surrogate pair)
17-
String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
18-
});
47+
let needToProcess = CONTAINS_ESCAPE.test(str);
48+
if (!needToProcess) {
49+
return str;
50+
}
51+
let ret = "";
52+
53+
for (let i = 0; i < str.length; i++) {
54+
if ((str[i] === "\\")) {
55+
const gobbled = gobbleHex(str.slice(i + 1, i + 7));
56+
if (gobbled !== undefined) {
57+
ret += gobbled[0];
58+
i += gobbled[1];
59+
continue;
60+
}
61+
62+
// Retain a pair of \\ if double escaped `\\\\`
63+
// https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
64+
if (str[i + 1] === "\\") {
65+
ret += "\\";
66+
i++;
67+
continue;
68+
}
69+
70+
// if \\ is at the end of the string retain it
71+
// https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
72+
if (str.length === i + 1) {
73+
ret += str[i];
74+
}
75+
continue;
76+
}
77+
78+
ret += str[i];
79+
}
80+
81+
return ret;
1982
}

0 commit comments

Comments
 (0)