2
\$\begingroup\$

I must access the elements of an object array very often by an identifier id, i.e.

[
{id:1, value:“test“, cat:2},
{id:2, value:“test“, cat:2},
{id:3, value:“test“, cat:2}, ...
]

To do so I use find, for example to fetch the value of object with id 3:

  SomeVal = myArray.find(x => x.id === 3).value

However, as I would never change the initial array after creation, and as the id of each item is well defined (I fetch the objects from my sql db), I was thinking to use the array index as identifier. I would use splice to create such array initially and I would start with id 1. I have around 5k objects.

This way I must not use find, but instead could access the array by the index directly:

 SomeVal = myArray[3].value

As my id starts with 1, the array would be of same size in the end.

I would think that’s an enormous performance boost, yet I have never seen anyone going such an approach when accessing elements by an identifier. What do you think?

\$\endgroup\$
1
  • \$\begingroup\$ Any example/real world scenario where you feel this approach is applicable or can be used? The above example is very specific one where all the conditions match \$\endgroup\$ – Sunil Chaudhary Dec 28 '19 at 19:13
3
\$\begingroup\$

Your implementation is basically a Map or Object that revolves around a very specific rule. That rule being the id directly correlates to the index in the array. The advantage an Array has over other data structures, with superior search speeds, is the fact that they are ordered. If order doesn't matter and you're purely using it to leverage search, Sets and Maps do a better job

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.