我们如何让 JSON.stringify 的速度提升一倍以上
JSON.stringify
is a core JavaScript function for serializing data. Its performance directly affects common operations across the web, from serializing data for a network request to saving data to localStorage
. A faster JSON.stringify
translates to quicker page interactions and more responsive applications. That’s why we’re excited to share that a recent engineering effort has made JSON.stringify
in V8 more than twice as fast. This post breaks down the technical optimizations that made this improvement possible.
JSON.stringify
是用于序列化数据的核心 JavaScript 函数。其性能直接影响整个网络的常见操作,从为网络请求序列化数据到将数据保存到 localStorage
。更快的 JSON.stringify
意味着更迅速的页面交互和更灵敏的应用程序。因此,我们很高兴地分享,最近的一项工程努力使 V8 中的 JSON.stringify
速度提升了一倍以上。本文将详细解析实现这一改进的技术优化。
The foundation of this optimization is a new fast path built on a simple premise: if we can guarantee that serializing an object will not trigger any side effects, we can use a much faster, specialized implementation. A "side effect" in this context is anything that breaks the simple, streamlined traversal of an object.
This includes not only the obvious cases like executing user-defined code during serialization, but also more subtle internal operations that might trigger a garbage collection cycle. For more details on what exactly can cause side effects and how you can avoid them, see Limitations.
此次优化的基础是一条新的快速路径,其前提很简单:如果我们能保证序列化对象不会触发任何副作用,就可以使用更快、更专门的实现。在此上下文中,“副作用”指的是任何会打断对象简单、流线型遍历的行为。
这不仅包括执行用户定义代码等明显情况,也包括可能触发垃圾回收周期的更微妙的内部操作。有关具体哪些情况会导致副作用以及如何避免它们的更多细节,请参见 限制。
As long as V8 can determine that serialization will be free from these effects, it can stay on this highly-optimized path. This allows it to bypass many expensive checks and defensive logic required by the general-purpose serializer, resulting in a significant speedup for the most common types of JavaScript objects that represent plain data.
只要 V8 能够确定序列化不会受到这些副作用影响,它就能继续沿这条高度优化的路径运行。这使得它可以绕过通用序列化器所需的许多昂贵检查和防御逻辑,从而对最常见的表示纯数据的 JavaScript 对象实现显著加速。
Furthermore, the new fast path is iterative, in contrast to the recursive general-purpose seria...