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'},
开发者_Go百科 { 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?JavaScript arrays are sparse, so no, you're aren't taking up extra memory like that. The downside though, and the reason why consoles display it like that, is that the length
property will be equal to your highest index + 1.
Some explanation:
All array indices are converted into strings and treated exactly the same as object properties. You can do the following test in the console:
var a = [];
a[100] = "hello";
a["100"]; // "hello"
a.hasOwnProperty("100"); // true
a.hasOwnProperty("0"); // false
To show that this isn't the same as a property that's declared but 'undefined':
a[0] = undefined;
a.hasOwnProperty("0"); // true
var objects = {
"20": { ID: 20, Description: "Item 1" }
"40": { ID: 40, Description: "Item 2" }
}
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.
精彩评论