I’m iterating through an array of arrays, pulling out the sub-arrays I need and discarding the rest.
var newArray = [];
for (var i = 0; i < oldArray.length; i++) {
if (oldArray[i][property] == value) {
newArray.push(oldArray[i]);
}
}
oldArray = newArray;
-
Is this the most memory-friendly way to do this?
-
Will garbage collection safely take care of the sub-arrays I did not push onto
newArray? - Will newArray be scattered across memory in a way that could prevent this method from scaling efficiently?
The javascript prototypal nature makes everything be an object. And all objects are maps, literally hash maps. Which means that when you are “pulling”, as you say, objects from one array into another, you are only copying their references.
So yes I would say it won’t bring you much memory problems, if you drop the references (at least in modern browsers). But the garbage collectors are implemented in different ways depending on the browser you are working with.
1 – Is this the most memory-friendly way to do this?
If you drop the references, yes it is a memory friendly way to do it. You don’t have any
freelike in c/c++, and for testing purposes on chrome i think you can callwindow.gc()to call the garbage collector. I think adeleteexists or existed but I don’t know how it works.2- Will garbage collection safely take care of the sub-arrays I did not append to newArray?
If there aren’t any other references pointing to them. Yes. Circular memory leaks were common in older browsers but with the new ones it’s safe to say yes.
3 – Will newArray be scattered across memory in a way that could prevent this method from scaling efficiently?
Yes it will be scattered across memory because in javascript arrays work like hashmaps or linked hashmaps (if i’m mistaken here someone pls correct me) but the garbage collector will take care of it, because it is used to work with maps. And again you are only working with references the objects will keep in the same place and you will only store references in the array.