是什么让预解析函数比完整解析更快?

What makes pre-parsing a function faster than a full parse?

为了提高性能JavaScript引擎有时只在实际调用函数时才完全解析函数。

例如,来自 Spidermonkey 源代码:

Checking the syntax of a function is several times faster than doing a full parse/emit, and lazy parsing improves both performance and memory usage significantly when pages contain large amounts of code that never executes (which happens often).

解析器可以跳过哪些步骤,同时仍然能够验证语法?

似乎在 Spidermonkey 中,一些节省来自于不发出字节码,比如在完全解析之后。在例如中进行完整解析V8 也包括生成机器码?

首先澄清一下:这两个步骤称为 "pre-parsing" 和 "full parsing"。 "Lazy parsing"描述了先做前者,需要时再做后者的策略。

pre-parsing 更快的两大原因是:

  • 它不构建 AST(抽象语法树),这通常是解析器的输出
  • 它不对变量进行范围解析。

解析器在准备代码生成时还执行了一些其他内部步骤,仅在检查错误时不需要这些步骤,但以上两个是主要步骤。

(完整)解析和代码生成是独立的步骤。