aboutsummaryrefslogtreecommitdiff
path: root/bench/snippets/escapeHTML.js
diff options
context:
space:
mode:
Diffstat (limited to 'bench/snippets/escapeHTML.js')
-rw-r--r--bench/snippets/escapeHTML.js78
1 files changed, 54 insertions, 24 deletions
diff --git a/bench/snippets/escapeHTML.js b/bench/snippets/escapeHTML.js
index 61bb74c7d..63e68861d 100644
--- a/bench/snippets/escapeHTML.js
+++ b/bench/snippets/escapeHTML.js
@@ -1,7 +1,27 @@
import { group } from "mitata";
import { bench, run } from "mitata";
-var bunEscapeHTML = Bun.escapeHTML;
+var bunEscapeHTML_ = globalThis.escapeHTML || Bun.escapeHTML;
+var bunEscapeHTML = function (str) {
+ if (str.length === 1) {
+ switch (str.charCodeAt(0)) {
+ case 34: // "
+ return """;
+ case 38: // &
+ return "&";
+ case 39: // '
+ return "'"; // modified from escape-html; used to be '&#39'
+ case 60: // <
+ return "&lt;";
+ case 62: // >
+ return "&gt;";
+ default:
+ return str;
+ }
+ }
+
+ return bunEscapeHTML_(str);
+};
const matchHtmlRegExp = /["'&<>]/;
@@ -13,6 +33,17 @@ const matchHtmlRegExp = /["'&<>]/;
* @public
*/
+const FIXTURE = require("fs")
+ .readFileSync(import.meta.dir + "/_fixture.txt", "utf8")
+ .split("")
+ .map((a) => {
+ if (a.charCodeAt(0) > 127) {
+ return "a";
+ }
+ return a;
+ })
+ .join("");
+
function reactEscapeHtml(string) {
const str = "" + string;
const match = matchHtmlRegExp.exec(str);
@@ -58,29 +89,28 @@ function reactEscapeHtml(string) {
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
-const long = ("lalala" + "<script>alert(1)</script>" + "lalala").repeat(9000);
-const short = "lalala" + "<script>alert(1)</script>" + "lalala";
-const middle =
- "lalala".repeat(2000) + "<script>alert(1)</script>" + "lalala".repeat(2000);
-const nothing = "lalala".repeat(9999);
-group(`long (${long.length})`, () => {
- bench("react's escapeHTML", () => reactEscapeHtml(long));
- bench("bun's escapeHTML", () => bunEscapeHTML(long));
-});
-
-group(`short (${short.length})`, () => {
- bench("react's escapeHTML", () => reactEscapeHtml(short));
- bench("bun's escapeHTML", () => bunEscapeHTML(short));
-});
+for (let input of [
+ // " ",
+ // "<script>alert('xss')</script>",
+ // "hello world",
+ // "hello world<script>alert('xss')</script>",
+ // "<",
+ // ">",
+ // `short value`,
+ `nothing to escape `.repeat(99999),
+ FIXTURE,
+]) {
+ group(
+ {
+ summary: true,
+ name: `"` + input.substring(0, Math.min(input.length, 32)) + `"`,
+ },
+ () => {
+ bench(`react's escapeHTML`, () => reactEscapeHtml(input));
-group(`middle (${middle.length})`, () => {
- bench("react's escapeHTML", () => reactEscapeHtml(middle));
- bench("bun's escapeHTML", () => bunEscapeHTML(middle));
-});
-
-group(`nothing (${nothing.length})`, () => {
- bench("react's escapeHTML", () => reactEscapeHtml(nothing));
- bench("bun's escapeHTML", () => bunEscapeHTML(nothing));
-});
+ bench(`bun's escapeHTML`, () => bunEscapeHTML(input));
+ }
+ );
+}
await run();