JavaScript 引擎 V8 釋出了 8.4 版本(測試階段),正式版本將在之後隨 Chrome 84 一起推出。8.4 版本帶來了一些面向開發人員的特性,主要亮點包括:
縮短啟動時間
WebAssembly 的基準編譯器(Liftoff)現在支援原子指令和大容量記憶體操作。這意味著使用者可以獲得更快的啟動時間。
更好的除錯
為了不斷改善 WebAssembly 的除錯體驗,開發團隊表示現在能夠檢查任何暫停執行或到達斷點的實時 WebAssembly 框架。這是透過重新使用 Liftoff 進行除錯來實現的。過去,所有具有斷點或逐步執行的程式碼都需要在 WebAssembly 直譯器中執行,這大大降低了執行速度。使用 Liftoff 會損失大約三分之一的效能,但是可以單步執行所有程式碼,並隨時進行檢查。
SIMD Origin Trial
SIMD 提案使 WebAssembly 能夠利用常用的硬體向量指令來加速計算密集型工作負載。V8 支援 WebAssembly SIMD 提案。要在 Chrome 中啟用此功能,請使用標記 chrome://flags/#enable-webassembly-simd 或註冊 origin trial 試用。Origin 試用版允許開發人員在功能標準化之前進行試驗,並提供反饋。
弱引用和終結器
提醒:弱引用和終結器是高階功能,它們取決於垃圾回收行為。垃圾回收是不確定的,可能根本不會發生。
JavaScript 是一種垃圾回收語言,這意味著當垃圾回收器執行時,程式無法再訪問的物件所佔用的記憶體可能會自動回收。除了 WeakMap 和 WeakSet 中的引用之外,JavaScript 中的所有引用都是強大的,可以防止對引用的物件進行垃圾回收。例如,
const globalRef = {
callback() { console.log('foo'); }
};
// As long as globalRef is reachable through the global scope,
// neither it nor the function in its callback property will be collected.
JavaScript 程式設計師現在可以透過 WeakRef 功能保留物件。如果弱引用所引用的物件也未得到強引用,則它們不會阻止對其進行垃圾回收。
const globalWeakRef = new WeakRef({
callback() { console.log('foo'); }
});
(async function() {
globalWeakRef.deref().callback();
// Logs “foo” to console. globalWeakRef is guaranteed to be alive
// for the first turn of the event loop after it was created.
await new Promise((resolve, reject) => {
setTimeout(() => { resolve('foo'); }, 42);
});
// Wait for a turn of the event loop.
globalWeakRef.deref()?.callback();
// The object inside globalWeakRef may be garbage collected
// after the first turn since it is not otherwise reachable.
})();
WeakRefs 的附帶功能是 FinalizationRegistry,該功能使程式設計師可以在物件被垃圾回收後註冊要呼叫的回撥。例如,下面的程式可能在 IIFE 中回收了無法訪問的物件後將日誌記錄到控制檯 42。
const registry = new FinalizationRegistry((heldValue) => {
console.log(heldValue);
});
(function () {
const garbage = {};
registry.register(garbage, 42);
// The second argument is the “held” value which gets passed
// to the finalizer when the first argument is garbage collected.
})();
結器計劃在事件迴圈上執行,並且永不中斷同步 JavaScript 的執行。
這些是高階且強大的功能,如果幸運的話,你的程式將不需要它們。
私有方法和訪問器
v7.4 中提供的私有欄位在對私有方法和訪問器的支援中得到了完善。從句法上講,私有方法和訪問器的名稱以 #
開頭,就像私有欄位一樣。以下是語法的簡要介紹。
class Component {
#privateMethod() {
console.log("I'm only callable inside Component!");
}
get #privateAccessor() { return 42; }
set #privateAccessor(x) { }
}
私有方法和訪問器具有與私有欄位相同的作用域規則和語義。可參閱 說明 以瞭解更多資訊。
請使用 git log branch-heads/8.3..branch-heads/8.4 include/v8.h
來獲取 API 更改列表。
[admin
]