概述
performance.now()是瀏覽器性能API的一部分,提供一個高精度、低誤差的時間測量方式,用以支持演算法分析和系統級優化。
一、performance.now單位
1、單位介紹
performance.now()返回當前時刻到navigationStart事件被觸發的時間差,依賴於操作系統高精度計時器提供的時間信息,單位為毫秒(ms)。
2、示例代碼
function testPerformance() { let t1 = performance.now(); // do some work here let t2 = performance.now(); console.log(`Time elapsed: ${t2 - t1} ms`); } testPerformance();
二、performance.now和date.now
1、性能比較差異
date.now()是JavaScript中的一個內置函數,返回當前的時間戳,不依賴操作系統計時器,但其精度較低,可能受到系統時間調整或線程調度等原因的影響。而performance.now()則依賴於操作系統計時器返回的測量結果,精度更高,但在運行過程中受到操作系統影響較大。
2、示例代碼
let t1 = Date.now(); // do some work here let t2 = Date.now(); console.log(`Time elapsed: ${t2 - t1} ms`); let t3 = performance.now(); // do some work here let t4 = performance.now(); console.log(`Time elapsed: ${t4 - t3} ms`);
三、performance.now js
1、API說明
performance.now()函數在JavaScript中作為瀏覽器提供的單一參數,可以與其他性能API結合使用,例如performance.mark()和performance.measure(),可以對性能分析過程進行更加細緻的測量和記錄。
2、示例代碼
performance.mark('startWork'); // do some work here performance.mark('endWork'); performance.measure('workTime', 'startWork', 'endWork'); console.log(performance.getEntriesByName('workTime')[0].duration);
四、performance.now在Firefox
1、Firefox中的差異
在Firefox中,performance.now()返回的結果是一個浮點數,代表自系統時間啟動以來所經過的時間。返回值精確度可以達到微秒級別,比其他現代瀏覽器更高。
2、示例代碼
let t1 = performance.now(); // do some work here let t2 = performance.now(); console.log('Time elapsed:', (t2 - t1) + 'ms');
五、performance.now和new date
1、new Date()的差異
new Date()是JavaScript中另外一個內置函數,能夠精確獲取當地時間,返回值會受到時區等諸多因素的影響,具有很強的可讀性。
而performance.now()則不關心時區等因素,更適合於瀏覽器性能優化。
2、示例代碼
let t1 = new Date(); // do some work here let t2 = new Date(); console.log('Time elapsed:', (t2 - t1) + 'ms'); let t3 = performance.now(); // do some work here let t4 = performance.now(); console.log('Time elapsed:', (t4 - t3) + 'ms');
六、performance.now() 用戶識別選取
1、用戶識別漏洞
performance.now()函數的返回值可以用於用戶行為識別,在較早版本瀏覽器中存在漏洞,被不法分子利用進行用戶行為跟蹤等商業行為,因此在實際應用中需要注意這個問題,並嚴格控制網站使用performance.now()功能的特權信息,避免用戶數據泄露。
2、代碼示例
function getUserData() { let t1 = performance.now(); // collect user data here let t2 = performance.now(); // send data to server sendData(t2 - t1); }
七、結語
通過本文的介紹,我們了解了performance.now()函數的原理和使用,包括其單位、與date.now()的比較、在JavaScript中的使用、在Firefox中的差異、與new Date()的性能差異、以及用戶信息識別問題等。在實際開發中,我們可以利用performance.now()函數對系統進行著重優化,提高Web應用程序的性能。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/150496.html