<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>在100万个key里查找300个key存在情况</title> </head> <body> <button class="flag-init">初始化数据(先点击一次)</button> <button class="flag-object">Object in(可多次点击)</button> <button class="flag-array">Array includes(可多次点击)</button> </body> </html>
let nr = { tsKeyObject: {}, tsKeyArray: [], init: (num = 1000000) => { if (nr.tsKeyArray.length == 0) { console.debug(`正在构建 ${num} 条数据`); console.time(); for (let i = 0; i < num; i++) { let item = nr.UUID(); nr.tsKeyObject[item] = true; nr.tsKeyArray.push(item); } console.timeEnd(); } }, findObject: () => { if (nr.tsKeyArray.length) { console.time(); let data = nr.newData(); let result = {}; data.forEach(item => { result[item] = item in nr.tsKeyObject; }); console.debug('find object (fast)', result) console.timeEnd(); } }, findArray: () => { if (nr.tsKeyArray.length) { console.time(); let data = nr.newData(); let result = {}; data.forEach(item => { result[item] = nr.tsKeyArray.includes(item); }); console.debug('find array (slow)', result) console.timeEnd(); } }, newData: (num = 300) => { let data = []; for (let i = 0; i < num; i++) { data.push(nr.UUID()); } return data; }, UUID: () => window["crypto"] && window["crypto"]["randomUUID"] ? crypto.randomUUID() : URL.createObjectURL(new Blob([])).split('/').pop(), } document.querySelector(".flag-init").addEventListener("click", function () { nr.init(); }); document.querySelector(".flag-object").addEventListener("click", function () { nr.findObject(); }); document.querySelector(".flag-array").addEventListener("click", function () { nr.findArray(); });