Skip to content

Commit 3029e0f

Browse files
authored
Merge pull request #27 from frenzzy/patch-1
Increase escapeHTML performance up to 10 times!
2 parents 995e464 + c583e76 commit 3029e0f

File tree

2 files changed

+50
-18
lines changed

2 files changed

+50
-18
lines changed

packages/babel-plugin-jsx-dom-expressions/src/shared/utils.js

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -212,14 +212,30 @@ const ATTR_REGEX = /[&<"]/g,
212212

213213
export function escapeHTML(html, attr) {
214214
if (typeof html !== "string") return html;
215-
return html.replace(attr ? ATTR_REGEX : CONTENT_REGEX, m => {
216-
switch (m) {
217-
case "&":
218-
return "&amp;";
219-
case "<":
220-
return "&lt;";
221-
case '"':
222-
return "&quot;";
215+
const match = (attr ? ATTR_REGEX : CONTENT_REGEX).exec(html);
216+
if (!match) return html;
217+
let index = 0;
218+
let lastIndex = 0;
219+
let out = "";
220+
let escape = "";
221+
for (index = match.index; index < html.length; index++) {
222+
switch (html.charCodeAt(index)) {
223+
case 34: // "
224+
if (!attr) continue;
225+
escape = "&quot;";
226+
break;
227+
case 38: // &
228+
escape = "&amp;";
229+
break;
230+
case 60: // <
231+
escape = "&lt;";
232+
break;
233+
default:
234+
continue;
223235
}
224-
});
236+
if (lastIndex !== index) out += html.substring(lastIndex, index);
237+
lastIndex = index + 1;
238+
out += escape;
239+
}
240+
return lastIndex !== index ? out + html.substring(lastIndex, index) : out;
225241
}

packages/dom-expressions/src/runtime.js

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -240,16 +240,32 @@ const ATTR_REGEX = /[&<"]/g,
240240

241241
export function escape(html, attr) {
242242
if (typeof html !== "string") return html;
243-
return html.replace(attr ? ATTR_REGEX : CONTENT_REGEX, m => {
244-
switch (m) {
245-
case "&":
246-
return "&amp;";
247-
case "<":
248-
return "&lt;";
249-
case '"':
250-
return "&quot;";
243+
const match = (attr ? ATTR_REGEX : CONTENT_REGEX).exec(html);
244+
if (!match) return html;
245+
let index = 0;
246+
let lastIndex = 0;
247+
let out = "";
248+
let escape = "";
249+
for (index = match.index; index < html.length; index++) {
250+
switch (html.charCodeAt(index)) {
251+
case 34: // "
252+
if (!attr) continue;
253+
escape = "&quot;";
254+
break;
255+
case 38: // &
256+
escape = "&amp;";
257+
break;
258+
case 60: // <
259+
escape = "&lt;";
260+
break;
261+
default:
262+
continue;
251263
}
252-
});
264+
if (lastIndex !== index) out += html.substring(lastIndex, index);
265+
lastIndex = index + 1;
266+
out += escape;
267+
}
268+
return lastIndex !== index ? out + html.substring(lastIndex, index) : out;
253269
}
254270

255271
// Hydrate

0 commit comments

Comments
 (0)