gpt4 book ai didi

javascript - 性能——我应该同时使用数组和对象来处理巨大的列表吗?

转载 作者:行者123 更新时间:2023-11-29 15:23:09 26 4
gpt4 key购买 nike

到目前为止,我的服务器已经处理了巨大的数组实体

主要是对实体做一个for循环每秒x次,检查一个实体是否在另一个实体的范围内(每个实体都有一个数组 entitiesInScope)通过执行 entitiesInScope.indexOf(entity),这是我程序的最大成本。

for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
for (var j = 0; j < entities.length; j++) {
var checkEntity = entities[j];
var idx = entity.entitiesInScope.indexOf(checkEntity);
if (idx >= 0) {
if (!check(checkEntity.state, entity.state)) {
entity.removeEntityInScope(idx);
//... remove: send checkEntity.id
}
} else {
if (check(checkEntity.state, entity.state)) {
entity.addEntityInScope(checkEntity);
//... add: send checkEntity.id, checkEntity.state
}
}
}
}

(我通过不对所有实体进行第二个循环来优化它,但这不是重点)

但是,我看到 Object 的 hasOwnPropertymuch faster比指数。另一方面,我也做了很多推送和拼接。因此,如果我添加一个实体对象,我也应该使用 delete (perf?)。

我应该:

-添加一个id为entity key的对象,使用hasOwnProperty(entity.id),如果为true则允许使用indexOf?

-添加一个带有实体键的对象,使用 hasOwnProperty(entity.id)(内存浪费)?

-继续数组

最佳答案

我建议迭代 entitiesInScope 以更新或删除那里的实体,因为您已经知道索引的方式,如果您向后遍历它,您可以删除项目而不会弄乱索引。

至于添加缺失的实体,我会在对象中标记已在 entitiesInScope 上的实体以进行快速查找,然后遍历实体并添加缺失的实体。代码将与此类似:

for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
var alreadyInScope = {}

for (var j = entity.entitiesInScope.length - 1; j >= 0; j--) {
var checkEntity = entity.entitiesInScope[j];

if (!check(checkEntity.state, entity.state)) {
var id = entity.entitiesInScope.splice(j, 1).id
} else {
alreadyInScope[checkEntity.id] = true;
}
}

for (var j = 0; j < entities.length; j++) {
if (alreadyInScope.hasOwnProperty(entities[j].id) == false) {
entity.entitiesInScope.push(entities[j])
}
}

}

关于javascript - 性能——我应该同时使用数组和对象来处理巨大的列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com