我试图从用作字典的对象中随机选择一个随机属性,以进行快速索引。
考虑以下代码:
//Create test dictionary
var dict = {};
for(var i = 0; i < 10000; i++) {
var num = Math.random() * 1000000 << 0;
dict[num] = { Id: num };
}
//Fuzz
const NUM_RUNS = 1000;
var start = new Date();
for(var i = 0; i < NUM_RUNS; i++)
getRandom(dict);
var end = new Date();
var runTime = (end.getTime() - start.getTime()) / 1000;
var timePerCall = (runTime / NUM_RUNS) * Math.pow(10,9);
console.log('Total Calls: ' + NUM_RUNS);
console.log('Total Runtime: ' + runTime + ' seconds');
console.log('Time Per Call: ' + timePerCall + ' nanoseconds');
function getRandom(dict) {
var keys = Object.keys(dict);
var index = keys[Math.random() * keys.length << 0];
return dict[index];
}
如您所见,Object.keys()
的使用非常昂贵,尤其是随着词典的增长。
我正在寻找实现字典中元素随机选择的最佳方法。当然,在字典中包含10000+个元素是一个极端的情况,但是我仍然希望能够处理它。
答案 0 :(得分:1)
如果无法缓存Object.keys
数组,则可以使用Proxy
维护自己的副本:
function generateKeyTracker (keysPropertyName) {
const set = new Set();
function defineProperty (target, property, descriptor) {
target[property] = descriptor.value;
if (set.has(property)) return true;
set.add(property);
target[keysPropertyName].push(property);
return true;
}
function deleteProperty (target, property) {
delete target[property];
if (!set.delete(property)) return true;
target[keysPropertyName] = target[keysPropertyName].filter(key => key !== property);
return true;
}
return {defineProperty, deleteProperty};
}
//Create test dictionary
var dict = new Proxy(
Object.defineProperty({}, '__keys', {
configurable: true,
enumerable: false,
writable: true,
value: []
}),
generateKeyTracker('__keys')
);
for(var i = 0; i < 1e4; i++) {
var num = Math.random() * 1e6 << 0;
dict[num] = { Id: num };
}
//Fuzz
const NUM_RUNS = 1e6;
var start = performance.now();
for(var i = 0; i < NUM_RUNS; i++)
getRandom(dict);
var end = performance.now();
var runTime = end - start;
var timePerCall = (runTime / NUM_RUNS);
console.log(`Total Calls: ${NUM_RUNS}`);
console.log(`Total Runtime: ${runTime} ms`);
console.log(`Time Per Call: ${timePerCall * 1e6} ns`);
function getRandom(dict) {
var index = Math.random() * dict.__keys.length << 0;
return dict[dict.__keys[index]];
}
这使用property creation和deletion上的陷阱来跟踪dict
的属性键,这些属性键存储在non-enumerable属性dict.__keys
中。 / p>