Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  17] [ 1]  / answers: 1 / hits: 19461  / 9 Years ago, mon, may 18, 2015, 12:00:00

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).



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.



UPDATE



snippet of filter experiment



      companyMasters = companyMasters.filter(function (obj) {
return obj.masterId != CompanyObj.masterId;
});

More From » jquery

 Answers
18

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.



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).


[#66564] Friday, May 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
griffinr

Total Points: 242
Total Questions: 91
Total Answers: 105

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
;