0

I have an API which returns me a collection which needs to be reordered for better performance later in code. Now, I'm wondering should I leave as collection of objects

var collection = [{
    "id": "d3d2d",
    "something": "win"
}, ...]

and use for later on:

for(var i in collection){bla = collection[i]something;}

or as a object

var object = {
    "d3d2d": {
        "something": "win"
    }
};

So that I can later use it like this

bla = object[i.need.id].something;

My point is if I use data as an object, I don't need to use "for" later in code. So which way will be faster? I need to note that later in code I need to compare a lot of data and I have really small response time!

EDIT1: Yes, ID's are unique.

EDIT2: Array vs. Object efficiency in JavaScript, thx @Daria

EDIT3: I need to iterate through arrays when I fetch them and I can use a lot of time to prepare data, BUT I need to save time once someone fetch data from me then I have around 20ms to do this and bunch of other stuff.

Community
  • 1
  • 1
Arcagully
  • 364
  • 1
  • 3
  • 13
  • 1
    Yes, the object lookup is much much much faster than iterating a whole array. So if you have to do lots of comparisons later, it makes sense to convert the array collection to that object (though [you shouldn't use `for in`](http://stackoverflow.com/q/500504/1048572) for that). – Bergi Aug 18 '15 at 13:15
  • 1
    Well, does it need to be *ordered*? Then there's not much of a choice. – deceze Aug 18 '15 at 13:15
  • 1
    They are different structures for different uses. If you need to iterate the object you'll need a loop anyway. – DontVoteMeDown Aug 18 '15 at 13:15
  • Iterating over the array once to transform it into a object can save you a lot of operations if you need to access the individual objects, later on. Collections of objects are a bit of a pain to work with, in that case, since every single time you'd want to access a specific object, you'd have to iterate over the array. – Cerbrus Aug 18 '15 at 13:17
  • "*which needs to be reordered for better performance later*" - seems you already know your answer? What exactly is your question? – Bergi Aug 18 '15 at 13:17
  • Maybe the next question will help you to understand deeply [http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript](http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript) – Daria Aug 18 '15 at 13:20
  • @Bergi thx for answer, also I didn't knew "for in" issue :) – Arcagully Aug 18 '15 at 13:20

1 Answers1

1

Provided the ID values are unique, as you've said, and you don't need any particular order to the objects, then in ES5 and earlier, you'd almost certainly want the second form, the object, not an array. (In ES6+ you'd probably want a Map.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875