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.

3
  • stackoverflow.com/a/8067678/3166303 Commented Oct 19, 2015 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. Commented Oct 19, 2015 at 12:27
  • See this link for your question Commented Oct 19, 2015 at 12:35

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.