2020 年 12 月 24 日(美國時間 23 日晚),Vue 做者尤雨溪在 twitter 連續發佈數條信息,具體主要大體以下:javascript
I remember there was a comparison of how much faster JS engines can parse string literals than actual JS (json strings vs. object literals) - anyone remember the link to that article/tweet?vue
我記得以前有一則對比 JS 引擎解析 JSON 字符串性能要優於對對象字面量的解析的文章,有誰記得文章的連接麼?java
Why do we need to keep these string literals? Because there are still cases where the component may not be on the initial screen and needs to be dynamically mounted. If you know the component is always going to be on the initially rendered markup, you can even drop the string!ios
爲何咱們須要保持這些字符串字面量?由於咱們仍然會存在組件不在首屏須要動態渲染的狀況。若是你知道你的組件一直都會出如今首屏,你甚至能夠直接刪除這些字符串!web
Application of this: mark part of your application SSG only. Affected components' render function is now just a string literal in the client code. Super cheap to parse. Imports originally used in the equivalent render fn code also get auto-treeshaken.json
這類應用:只對部分應用生成靜態內容(SSG)。受到影響的組件的 render 方法在客戶端只是字符串字面量,編譯的消耗很是低。原先在 render 方法中使用的引入也會被自動 treeshakenmarkdown
I'm excited about this because this is already totally feasible with Vue 3's compiler infra (and some of this is already applied in more strictly constrained scenarios e.g. VitePress). Need to do some benchmarking to see the real world impact of this though.app
我對此感到激動由於這在 Vue3 的編譯器基礎設施中已是可行的(而且一部分已經在約束更嚴格的 VitePress 中實現),雖然仍然須要進行一些現實場景例子的性能測試。svg
這裏只摘抄了一部分主要的內容,其餘還有不少跟別人討論的以及細節的內容,你們能夠自行去 twitter 翻一翻尤老師的發言記錄。工具
咱們簡單聊聊尤老師這是在說什麼。尤老師詢問的文章是這篇Javascript 性能 2019, 這篇文章裏面提到了一個點,那就是 JSON.parse(objectString)的性能要比對象字面量要好。
什麼意思呢?咱們來看一組對比代碼:
const obj = JSON.parse('{"a": "b"}')
// 和
const obj = { a: "b" }
複製代碼
這兩句代碼的最終結果,都是 obj 指向一個只有a
屬性,其值爲字符串"b"
的對象。而文章的結論是上面的方案要比下面的方案性能更好(固然你別拿這兩句代碼去測試,要測試請把對象內容放大到足夠大)。
這可能會出乎一些同窗的意料,由於從普通視角看,對一行代碼多執行來一步JSON.parse
方法調用,理論上性能會更差。
那麼爲何會這樣呢?由於 JS 是解釋語言。其實執行第二句代碼的時候,對於 JS 引擎來講, 他也是首先須要解析整一句語句, 而後對其進行詞意分析, 語義分析等等編譯流程, 最後生成變量和對象。 也就是說最開始咱們的對象字面量,在 JS 引擎眼裏其實也就是字符串
那爲何JSON.parse
性能更好呢? 由於 JSON 的關鍵字比 JS 少太多了, JS 引擎對對象字面量作的編譯,要考慮全部 JS 關鍵字和語法, 而JSON.parse
只須要考慮 JSON 的語法和關鍵字, 那麼性能更好天然很好理解了,簡單來講就是if else
更少(只是舉例,別認真)
而後尤老師的重點就是,Vue3 的編譯引擎能夠很是適合地進行相似的優化,尤爲是集成度更高的 VitePress 工具,已經集成了一部分相似優化。
至於爲啥尤老師在昨天晚上這麼激動地發佈這麼多信息,我猜,大概跟前一天 React 發佈了ServerComponent
有關係吧。。。
將來尤老師有什麼新的信息在 twitter,只要內容跟 Vue3 有關,咱們都會第一時間進行分析分享,有興趣的同窗關注一波哦!
本文首發於BestVue3,一個分享優質Vue3學習內容以及開發優質Vue3開源項目的網站!