profile image

kaitokosugeppp

更新日:

以下のようなオブジェクト配列を作成し、要素検索を行う。
const NUM_ITEMS = 100000;
// 10万件のオブジェクト配列を作成
const objArray = Array.from({ length: NUM_ITEMS }, (_, i) => ({
   id: i,
   name: `Item ${i}`,
}));

// 検索する値(配列の最後の要素を検索)
const searchId = NUM_ITEMS - 1;
以下3つの方法で最も速さが期待できるのはどれでしょう!
// 1. some() の速度計測
console.time('some');
const foundSome = objArray.some((item) => item.id === searchId);
console.timeEnd('some');

// 2. includes() の速度計測(idの配列を作成してから includes を使用)
const idArray = objArray.map((item) => item.id);
console.time('includes');
const foundIncludes = idArray.includes(searchId);
console.timeEnd('includes');

// 3.Setの速度計測
const idSet = new Set(idArray);
console.time('has');
const foundHas = idSet.has(searchId);
console.timeEnd('has');