Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of accessing data in an object

In some of the projects I'm working on as part of my day job, I need to access data in very large JS objects (on the order of thousands of key-value pairs). I'm trying to improve the efficiency of my code, so I came up with a few questions:

  1. What is the runtime complexity of JS when accessing a field in such an object? My initial hunch is that it's O(n)
  2. Is there a difference when accessing through dot notation or bracket notation? (e.g. obj.field vs obj[field])
  3. I'm guessing there is a different answer for different runtime engines - is there a place where I can see the difference between them?
like image 514
DanielR Avatar asked Jul 23 '17 15:07

DanielR


People also ask

What is the complexity of object keys?

For objects with thousands of named properties, our implementation indeed uses a hash table (as the question guessed), and that means complexity of Object. keys() is O(n log n). That's because a hash table (of course) stores entries in its own order.

Which is faster object or array?

Objects will be used when we need fast access, insertion and removal of an element as objects are comparatively much faster than the arrays in case of insertion and removal.

Are JavaScript objects O 1?

JavaScript objects are implemented using Hash tables under the hood. One thing about Hashing table is that — Hash tables Retrieve method have O(1), constant time complexity because of the use of a hashing function.

Is array Pop o 1?

Arrays. Because it takes a single step to access an item of an array via its index, or add/remove an item at the end of an array, the complexity for accessing, pushing or popping a value in an array is O(1).


1 Answers

Javascript objects are actually Hashes, so the complexity is O(1) for all engines.

obj.field is an alias for obj['field'], so they have the same performances.

You can find some JS hashes performance tests here, unfortunately only for your browser engine.

like image 128
Marco Vanetti Avatar answered Oct 01 '22 21:10

Marco Vanetti