#1461·acorn

currentVarScope/currentThisScope walk the scope stack per statement, so deeply nested blocks parse in quadratic time

Author: tonioloewaldCreated Sep 26, 2026Updated Sep 27, 2026

A small performance note, not a security report. Parsing N nested blocks that each contain a statement is quadratic in N, while N nested empty blocks are linear:

javascript
import { parse } from 'acorn' // 8.18.0, Node 22

const time = (src) => { const t = performance.now(); parse(src, { ecmaVersion: 'latest' }); return performance.now() - t }
for (const n of [500, 1000, 2000, 3000]) {
  console.log(n,
    time('{a;'.repeat(n) + '}'.repeat(n)).toFixed(1) + 'ms',  // with a statement
    time('{'.repeat(n) + '}'.repeat(n)).toFixed(1) + 'ms')    // empty
}
// 500  1.9ms  0.2ms
// 1000 4.1ms  0.1ms
// 2000 15.0ms 0.3ms
// 3000 34.2ms 0.4ms

A CPU profile puts the time in currentVarScope / currentThisScope (src/scope.js). Each walks scopeStack from the top down to the nearest function-like scope. Every block pushes a scope, so each statement at depth N walks N entries.

It only shows at thousands of nesting levels, so it's low priority. If it's worth fixing, one option that leaves the plugin-facing scope data alone is to keep a parallel stack of indices of the var-like (and this-like) scopes, pushed and popped in enterScope/exitScope, and read the top instead of walking.

(Found while bounding parse cost for a sandbox that parses untrusted AJS source with acorn. We cap the source size on our side, so nothing is urgent here.)