So I have a bunch of (10000+) objects that I need to remove/replace for simplicity, we can presume that the object contains a (String) Unique 'id'. The items often need to be renamed (change id), but not as often as it's looked up
{ id: 'one' }, { id: 'two' }, ...
If I place them inside an 'associative array' (bad practise), I can access them quickly, but need to loop (slow) to remove (NOTE: This doesn't actually work, because findIndex only works correctly on proper arrays, but a for loop would do the same thing)
arr = [];
arr['one'] = { id: 'one' };
arr['two'] = { id: 'two' };
arr.splice(arr.findIndex(function(i) { return i.id === 'one'; }), 1);
If I place them in a normal array, I have to loop (slow) to find the item by ID, and deleting would require a loop (slow) as well (Edit: In my particular case deleting it should be relatively quick as I'll have already looked it up and have a reference, but obviously slower if I lose reference)
arr = [{ id: 'one', }, { id: 'two' }];
arr.splice(arr.findIndex(function(i) { return i.id === 'one'; }), 1);
or, if I store them the obviously correct way, I have the choice of using the delete
keyword (which I've always been told is slow and breaks optimisations), or setting as undefined (which leaves me with a lot of elements that exist - memory leaks? and slower loops)
obj = { one: { id: one }, two: { id: two } };
delete obj['one'];
...
obj = { one: { id: one }, two: { id: two } };
obj['one'] = undefined;
I'm thinking that delete object[...]
is the best choice, but I'm interested in other's feedback. Which should I use, and why?