I’m looking for an easy and efficient way to pigeon-hole business objects to be recalled later by ID in some sort of dictionary. I have this method working but it appears it may be unnecessarily using a lot of memory.
var objects = [{ ID: 20, Description: 'Item 1'},
{ ID: 40, Description: 'Item 2'},
{ ID: 60, Description: 'Item 3'}];
var objectsByID = [];
$.each(objects, function (index, o) {
objectsByID[o.ID] = o;
});
var itemID40 = objectsByID[40];
Firebug tells me that objectsByID has undefined array elements in-between the ID numbers that have been added, like so:
[undefined, ... ,
Object { ID=20, Description="Item 1"}, ... ,
Object { ID=40, Description="Item 2"}, ... ,
Object { ID=60, Description="Item 3"}]
Are these array indexes actually assigned and using memory, or is this a conceptual view?
Also, should I be doing this?
Don’t use an array. Use an object and duplicate the key. You can still treat it as an array but with an array it will create spaces 1-19 here you just have two keys which happen to be called “20” and “40”.
Of course you can just use arrays anyway because it doesn’t really matter that much in terms of memory usage with a bunch of undefined objects. We don’t allocate blocks of memory equivelant to the largest block in the array like we do in C.