1

I need to search in an object. In a real project, there are many keys and objects that need to be checked. Which search method to use for better performance?

if(object.test1) console.log('true')
if(object.test2) console.log('true')
if(object.test3) console.log('true')

or

for (const key in object) {
   if(key=='test1') console.log('true')
   if(key=='test2') console.log('true')
   if(key=='test3') console.log('true')
}

Is there a difference in execution speed? Or maybe there is another way better than these?

Roman
  • 175
  • 2
  • 3
  • 15
  • You definitely shouldn't loop over every single key in the object to just check if 3 keys exist... – Unmitigated Mar 26 '23 at 04:54
  • The best and most accurate way would be [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn). See also [this question](https://stackoverflow.com/q/1098040). – InSync Mar 26 '23 at 04:56
  • @Unmitigated And if in a real project there are 100 keys? And 100 objects to check. Which method will be more efficient? – Roman Mar 26 '23 at 04:59
  • The first one would be better performance assuming your object has a bunch of properties that you’re not checking. If you’re checking all properties it doesn’t matter. – James Mar 26 '23 at 06:02
  • 2
    If you know the key, then direct access is the best performance approach. If you don't know if the key, then you have no choice but loop. In your specific case the direct approach is the best option. – piskunovim Mar 26 '23 at 07:33

1 Answers1

-1

You can use Object.keys() method to get all the keys in an array and then use Array.includes() method to check whether your key is present.

Both methods have a time complexity of O(n).

Spoorthy
  • 17
  • 3
  • First, the question wasn't about it. Secondly, instead of starting to cycle through the keys right away, you suggest making an array first. – piskunovim Mar 26 '23 at 07:39