0

at the moment I am using an object to simulate an associatve array. The object acts like a one to many relationship table from mysql For Example:

var obj = {
  105: [],
  200: []
  //...
}

My property names are only numeric so I found out that I could use an array, too. But then the empty entries between the indices are filled with undefined.

var arr = [];
arr[10] = "Value";
arr[15] = "Value 2";
//arr => [undefined*10, "Value", undefined*4, "Value 2"]

So when I am going to iterate over that array I have to check if the value at the current index is set.

So the question is, which of the solutions is faster or better. Using an object or an array where the empty space between the indizes is filled with undefined values.

leeor
  • 17,041
  • 6
  • 34
  • 60
Genmais
  • 1,099
  • 2
  • 9
  • 14
  • http://stackoverflow.com/a/8067678/3166303 – leeor Oct 19 '15 at 12:26
  • In your case object should possibly use less memory. Iterating both structures is mostly the same, however you have to remember that object properties in JavaScript don't have order. – VisioN Oct 19 '15 at 12:27
  • [See this link for your question](http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript) – Muhammad Naufal Oct 19 '15 at 12:35

2 Answers2

2

If you need a key-value association, you need an object.
If you want an ordered list in which the keys don't really matter, an array it is.

FYI, the indices "between" set indices in an array are not actually "filled" with undefined; you merely get the undefined value when you try to access a non-existing property on any object:

({}).foo; // undefined
deceze
  • 510,633
  • 85
  • 743
  • 889
0

You are asking which is "faster or better". For "better" many possible answers exist, but "faster" has a clearer answer: as others pointed out there is hardly any speed difference between Object and Array. Both have the same roots in the prototype hierarchy. An Array's empty values are not "filled".

Regarding your use case the bottleneck will not be the object, but how you loop it! This actually does make a difference: for loops are faster than any other way of looping. But you have the problem of the non-continuos numeric indices.

Therefore: just benchmark how long it takes if you do

  • for(key in object)
  • keys = Object.keys() and for(var i = 0; i < keys.length; i++)

as these two should be your fastest options.

B M
  • 3,893
  • 3
  • 33
  • 47