簡體   English   中英

為什么async-await比在一起運行它們時的promises慢得多

[英]why is async-await much slower than promises when running them together

我發現在某些情況下運行async-await會慢得多。

 <html> <script> function makeAPromise() { return Promise.resolve(Math.random()); } function usingPromises() { const before = window.performance.now(); return makeAPromise().then((num) => { const after = window.performance.now(); console.log('Total (promises): ', after-before, 'ms'); return num; }) } async function usingAwait() { const before = window.performance.now(); const num = await makeAPromise(); const after = window.performance.now(); console.log('Total (await): ', after-before, 'ms'); return num; } function runBoth() { usingAwait(); usingPromises(); } runBoth(); </script> <button onclick="usingPromises()">usingPromises</button> <button onclick="usingAwait()">usingAwait</button> <button onclick="runBoth()">both</button> </html> 

IMO在的console.log usingPromises應該打印相似的結果的一個在usingAwait 但實際上,我得到:

總計(承諾):0.25毫秒

總計(等待):2.065毫秒

此外,在頁面加載后,如果我點擊'usingPromises'或'usingAwait'按鈕,我會得到類似的結果。 (單獨跑步時速度都很快)

總計(承諾):0.060000000026775524毫秒

總計(等待):0.08999999999650754毫秒

但如果我點擊'both'按鈕,'await'版本比promises版本慢〜3-4倍。

我有一個真正的應用程序在初始化時運行許多promises / async-await函數,我發現將一些async-await函數替換為它們的“相等”promises版本可以節省大量的加載時間(~200ms)。

有人可以解釋為什么會這樣嗎? async-await是否也使用與promises相同的作業隊列(微任務)? 是否應該使用promises而不是async-await,是否有最佳實踐?

  • 在mac上運行chrome 62

謝謝

當使用按鈕Both運行時,您的第一個結果是誤導性的。 諾分辨率測序在microtask事件隊列:這樣一個得到與打印console.log之前其他的,但它是console.log帶來額外延遲到第二,因為它創建了第二承諾之間發生處理其決議。

如果你將runBoth定義為:已經是一個改進:

Promise.resolve().then(usingAwait).then(usingPromises)

現在兩個承諾都將在微任務中創建,第一個承諾將在創建第二個承諾之前得到解決和處理。 這將導致更公平的比較,其中console.log不在任何時間測量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM