介绍
🌐 Introduction
我们正处于 JavaScript 的第三时代,如今的普遍趋势是用 Rust 或 Go 编写 JavaScript 工具,以获得性能提升。
🌐 We are in The Third Age of JavaScript, the common trend right now is to author JavaScript tools in Rust or Go for their performance gains.
但是开发 JavaScript 工具本身就很具有挑战性,更别说用 Rust 来编写它们了。我在学习这些技术时经历了很多困难,我希望很少有人要经历同样的挣扎旅程。
🌐 But authoring JavaScript tools are challenging, let alone writing them in Rust. I have struggled a lot when learning these technologies, and I wish fewer people to take the same struggling journey.
我想通过撰写这份指南为社区做出自己的贡献,这样你就不必经历我曾经历的同样旅程。
🌐 I want to make my own contribution to the community by writing this guide, so you don't have to take the same journey as I had.
在 Rust 方面只有少数开发者,我希望看到你来到这里加入我们,这样我们就能为大家打造更好、更快速的工具。
🌐 There are only a handful of developers on the Rust side, and I would like to see you here and join us, so we can build better and faster tools for everyone to enjoy.
概览
🌐 Overview
在本指南中,将应用标准的编译器前端阶段:
🌐 For this guide, the standard compiler frontend phases will be applied:
Source Text --> Lexer --> Token --> Parser --> AST编写一个 JavaScript 解析器相当容易,10% 是架构决策,90% 是对细节的艰苦工作。
🌐 Writing a JavaScript parser is fairly easy, it is 10% architectural decisions and 90% hard work on the fine-grained details.
架构决策主要会影响两个类别:
🌐 The architectural decisions will mostly affect two categories:
- 我们解析器的性能
- 使用我们的 AST 真是太棒了
在用 Rust 构建解析器之前,了解所有选项和权衡将使我们的整个过程更加顺利。
🌐 Knowing all the options and trade-offs before building a parser in Rust will make our whole journey much smoother.
性能
🌐 Performance
编写高性能 Rust 程序的关键是减少内存分配和降低 CPU 占用。
🌐 The key to a performant Rust program is to allocate less memory and use fewer CPU cycles.
仅仅通过寻找堆分配的对象,如 Vec、Box 或 String,就能大致看出内存分配的位置。推断它们的使用情况会让我们了解程序的运行速度——分配的越多,程序就越慢。
🌐 It is mostly transparent where memory allocations are made just by looking for heap-allocated objects such as a Vec, Box or String. Reasoning about their usage will give us a sense of how fast our program will be - the more we allocate, the slower our program will be.
Rust 给了我们零成本抽象的能力,我们不需要过多担心抽象会导致性能变慢。注意我们的算法复杂度,我们就可以顺利进行。
🌐 Rust gives us the power of zero-cost abstractions, we don't need to worry too much about abstractions causing slower performance. Be careful with our algorithmic complexities and we will be all good to go.
INFO
你也应该读读《锈迹表现书》(https://nnethercote.github.io/perf-book/introduction.html)。
Rust 源代码
🌐 Rust Source Code
每当无法推断函数调用的性能时,不要害怕点击 Rust 文档中的“源代码”按钮并阅读源代码,它们大多数时候都很容易理解。
🌐 Whenever the performance of a function call cannot be deduced, do not be afraid to click the "source" button on the Rust documentation and read the source code, they are easy to understand most of the time.
INFO
在浏览 Rust 源代码时,搜索一个定义就是简单地查找 fn function_name、struct struct_name、enum enum_name 等。这是 Rust 语法保持一致的一个优势(相比于 JavaScript 😉)。
