Skip to content

Parser: end tags nobody opened, repeated <form> and SVG-cased names still scan every open element #2548

Closed

Description

@gusnips

On master (a4c60b8), after #2481, three lookups still read the whole open-element stack once per tag:

  • onclosetag: this.stack.lastIndexOf(name), for an end tag whose name is not open.
  • emitOpenTag: this.stack.includes("form"), on every <form>.
  • readTagName: this.stack.includes(adjusted), for an SVG-cased name once a foreign context is open.

Each is quadratic in the nesting depth, and a page that triggers it is small:

import { Parser } from "htmlparser2";

const n = 20_000;
const html = "<b>x".repeat(n) + "</i>".repeat(n); // 156 KB
const started = performance.now();
new Parser({ onclosetag() {} }).end(html);
console.log(performance.now() - started);

Measured on a heavily loaded machine, so the ratios matter more than the absolute times:

input n size master, Node 24.21 master, Bun 1.4.2
<b>x x n, then </i> x n 10,000 78 KB 6.5 s 4.7 s
20,000 156 KB 23.9 s 39.2 s
<b>x x n, then <form> x n 10,000 98 KB 2.9 s 2.8 s
20,000 195 KB 9.1 s 8.5 s
<svg><foreignObject>, <b>x x n, then <clippath> x n 10,000 137 KB 6.6 s 7.6 s
20,000 273 KB 20.6 s 36.1 s

12.0.0 has the same shape: 40,000 stray end tags (313 KB) took 46 s there and 107 s on master. For anything that parses HTML it did not write, that is a cheap way to hold a process for minutes.

Counting reads of stack with the countArrayReads helper from Parser.spec.ts shows it without timing noise: 500 <div> and then 500 </span> read the stack 250,499 times, and 2,000 of each read it 4,001,999 times.

A count of open elements per name, kept in push, pop and reset, answers all three in one lookup. A comment on #2481 suggests the same thing (#2481 (comment)). I have a patch with tests, and can open a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions