views:

190

answers:

4

I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two thousand odd entries in the array with "undefined." With hundreds of such arrays kicking around in active memory, I'm worried the overhead of hundreds of thousands of useless array items could start to slow the program down. Will it?

+4  A: 

Yes, most likely. You should consider using a JavaScript object instead:

var years = {2009: 'Good', 2010: 'Better'};
Brian McKenna
Why use strings for years?
apphacker
@apphacker: You're right, I've changed it.
Brian McKenna
It doesn't matter, as keys they're equivalent. It's just a matter of taste.
Justin Johnson
if you put the years in quote marks, it's JSON compatible.
Breton
+7  A: 

When you set the value of a numeric index higher than the current length of your array, the length property is affected.

In brief, you should use an Object:

var data = {};
data[year] = "some data";

// or
var data = {
  2009: "2009 data",
  2010: "2010 data"
};

Now I answer the question title: "Does JavaScript populate empty array items?"

No, as I said before, only the length property is changed, (if necessary, only if the index added is larger than the current length), length is incremented to be one more than the numeric value of that index.

The Array.prototype methods work assuming that the array object will have its indexes starting from zero.

The previous indexes don't really exist in the Array object, you can test it:

var array = [];
array[10] = undefined;

array.hasOwnProperty(10); // true
array.hasOwnProperty(9);  // false

In conclusion, arrays are meant to contain sequential indexes, starting from zero, if your properties don't meet those requirements, you should simply use an object.

CMS
Thanks - this really helped clarify how the arrays work. I've switched to object literals.
futuraprime
A: 

Well, if you iterate over many thousands of undefined, it will affect overall program speed, not sure if you'll notice it though.

apphacker
You *might*: 1024 empty nodes takes about 2ms in FF 3.5.6
Justin Johnson
A: 

On the other hand, sometimes a sparse array is simpler to use than a custom object, and arrays have such handy methods available.

In a calendar application I begin with objects for each year in use, but each year consists of a twelve member (months array) and each 'month' is a sparse array of significant dates, whose lengths depend on the highest date of that month that has any data.

kennebec