在下面的代碼中,創建了100萬個相同長度的字串。 然后,它們被回圈使用以找到一個匹配的字串。 第一次運行的字串比第二次運行的字串長 3 倍。
預期的結果是,對不同長度的字串進行平等比較所需的時間不會因為 "字串互換 "而發生變化。然而,結果顯示,一個長度為3倍的字串需要大約3倍的時間來做平等檢查。這是為什么呢?
import { v4 as uuidv4 } from 'uuid'/span>;
export const uuid = ()=> {
return uuidv4()。
};
function createSingleId(howManyUuidsInOneId1: number) {
let id = ''/span>;
for (let j = 0; j < howManyUuidsInOneId1; j ) {
id = uuid()。
}
return id。
}
function generate(howManyIds: number, howManyUuidsInOneId: number) {
const ids = [];
for (let i = 0; i < howManyIds; i ) {
ids.push(createSingleId(howManyUuidsInOneId) )。
}
return ids;
}
const main = (howManyIds: number, howManyUuidsInOneId: number) => {
const ids = generate(howManyIds, howManyUuidsInOneId)。
const toFind = createSingleId(howManyUuidsInOneId)。
console.log(`Sample id being compared: '${toFind}') 。
const before = new Date().getTime() 。
ids.filter(id =>id == toFind)。
console。 log(`Took '${new Date(). getTime() - before}ms'來回圈比較'${howManyIds}',當堆疊'${howManyUuidsInOneId}'在單一id`)。)
};
main(1000000, 3) 。
main(1000000, 1) 。
輸出:
Sample id being compared: 'dc03bf00-6f2a-48d9-b3ca-b6ac45782c5cefaa92c0-9372-4f47-bcec-f9fbb41d4625e0c5c278-b574-4a9f-a77e-110cbc6bf601'
花了 '64ms'回圈并等量比較'1000000'當堆疊'3' 在單一id
樣本 id被比較。'07e693ce-49a1-4cc6-90e1-0bd99629123b'
花了 '19ms' 回圈并等價比較'1000000' 當堆疊'1' 在 單個id
> node --version
v15.14.0。
uj5u.com熱心網友回復:
預期的結果是,對不同長度的字串進行等價比較的時間不會因為'字串互換'而發生變化。
不,字串互換只意味著對于某些字串,你知道它們是相同的,因為它們被存盤在相同的位置,例如,對于從相同的字串字元創建的字串值。但并不是所有的字串(尤其是動態創建的字串)都得到了互換,而且不同的記憶體地址并沒有說明字串的內容。如果記憶體位置檢查失敗,你仍然需要像往常一樣比較字串的內容。
一些例子來證明這一點:
。function generateString(len) {
let x = ""/span>;
for (let i=0; i<len; i ) x = String. fromCharCode(64 i%64)。
return x;
}
function time(callback, desc) {
const before = performance.now()。
const res = callback();
console.log(`Took ${performance。 now()-before}ms到${desc}`)。)
returnres。
}
const strLen = 5000000;
const a = generateString(strLen)。
const b = generateString(strLen);
console.assert(a == b)。
const str = a;
time(() => str ==a, 'compare a with itself') 。
time(() => str === b, 'compare a with b');
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
a和b具有相同的內容,但是是不同的字串物件(在記憶體中),因為它們是在不同的generateString呼叫中積累的。str參考了a的相同的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/324429.html
標籤:
上一篇:??酷炫回應式電競博客網頁設計??(HTML+CSS+JavaScript)web前端期末大作業
下一篇:在XAML中添加一個資源參考
