0

I have a humongous set of objects which can either be represented as

const object = {
    <SOME_KEY_0>: {
        type: <SOME_TYPE>,
        value: <SOME_VALUE>
    },
    <SOME_KEY_1>: {
        type: <SOME_TYPE>,
        value: <SOME_VALUE>
    },
    // so on...
}

return object[<SOME_KEY_1>];

or as

const array = [
    {
        key: <SOME_KEY_0>,
        type: <SOME_TYPE>,
        value: <SOME_VALUE>
    },
    {
        key: <SOME_KEY_1>,
        type: <SOME_TYPE>,
        value: <SOME_VALUE>
    },
    // so on...
]

return array.filter(elem => elem.key === <SOME_KEY_1>);

Which structure would be more efficient in finding a specific object identifiable by the key?

Also, we can assume array.filter() can be replaced with a for-loop to allow premature break.

Jun Park
  • 508
  • 1
  • 6
  • 20
  • `x[y]` is faster. – Marty Nov 27 '17 at 07:05
  • it's fastest to iterate an array, rather than an objects enumerable keys – synthet1c Nov 27 '17 at 07:06
  • Might be the good reference. https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object – moon Nov 27 '17 at 07:07
  • Your first structure would be more efficient if you are finding all elements by the key (probably less than `O(n)`, depends on the implementation of the browser.) – Derek 朕會功夫 Nov 27 '17 at 07:08
  • I will be running this on node.js server-side and all elements will be looked up by the *key* and *key only*. Looks like object key reference is more favored. But what if I have to build the object/array, would it be similar in performance if I do `array[i] = stuff` or `object[key] = stuff`? – Jun Park Nov 27 '17 at 07:16
  • Use first approach ; Object.keys() will return an array; try filter on top of that array; – Rajkumar Somasundaram Nov 27 '17 at 07:48

0 Answers0