题意:"Javascript 中最快的从数组中移除对象的方法"
问题背景:
Working on app where speed is crucial, the arrays are huge and the objects contained within the arrays.
"正在开发一个对速度要求极高的应用,数组非常大,并且数组中包含对象。"
I experimented with grep and filter and can not see significant speed difference, varies +- 5ms , also tried looping through array and using .splice(i,1);
(same results).
"我尝试了使用 `grep` 和 `filter`,但没有看到显著的速度差异,波动在 ±5 毫秒左右。我还尝试了通过遍历数组并使用 `splice(i, 1);`(结果相同)。"
I have a fast machine, if it always take more or less the same time on fast machine, does that mean it will take more or less same time on older machine?
"我有一台速度很快的机器,如果在这台快机器上花费的时间总是差不多相同,那是否意味着在旧机器上也会花费差不多相同的时间?"
Is there faster way to remove an object from array?
"有没有更快的方法从数组中移除对象?"
Want to do something like this:
"想要做类似这样的事情:"
var filterTime = performance.now();
doStuff1();
var filterTimeEnd = performance.now();
var grepTime = performance.now();
doStuff2();
var grepTimeEnd = performance.now();
and then store the differences in cookie, so the next time the page loads or is refreshed, execute most efficient way: removing object from array.
"然后将差异存储在 cookie 中,以便下次加载或刷新页面时,执行最有效的方法:从数组中移除对象。"
UPDATE
snippet of filter experiment
companyMasters = companyMasters.filter(function (obj) {
return obj.masterId != CompanyObj.masterId;
});
问题解决:
Any solution in which you need to iterate the array to find a single item would seem to indicate that you have a problem with the data structure you are using. Rather than storing your objects in a numerically indexed array, perhaps your should be storing them in an object where keys are the masterId
values that you are going to be trying to do lookups against. At a very minimum, if you need to keep your objects in a numerically index array for some other reason, you could consider building a separate object within which you map the masterId
values to the index in the main array where the object resides.
"任何需要遍历数组以查找单个项的解决方案都表明你使用的数据结构存在问题。与其将对象存储在一个数字索引的数组中,不如将它们存储在一个对象中,其键是你要查找的 `masterId` 值。至少,如果你因为其他原因需要将对象保留在数字索引数组中,可以考虑构建一个单独的对象,在其中将 `masterId` 值映射到主数组中对象所在的索引。"
So rather than something like this:
"所以,与其这样做:"
[
{
masterId: 'foo',
...
},
{
masterId: 'bar',
...
},
...
]
You would build your data structure like this:
"你可以像这样构建你的数据结构:"
{
foo: {
masterId: 'foo',
...
},
bar: {
masterId: 'bar',
...
},
...
}
This would allow your code to look like this:
"这将允许你的代码像这样:"
var needle = CompanyObj.masterId;
// delete object set for 'needle' property
delete companyMaster[needle];
This gives you an operation with O(1)
time complexity instead of O(n)
.
"这将使你的操作具有 O(1) 时间复杂度,而不是 O(n)。"