Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of key lookup in JavaScript object

I just read this question: are there dictionaries in javascript like python?

One of the answers said that you can use JavaScript objects like Python dictionaries. Is that true? What is the performance of a key lookup in an object? Is it O(1)? Is adding a key to the object also constant time (hashing)?

like image 406
Saher Ahwal Avatar asked Oct 09 '11 02:10

Saher Ahwal


People also ask

Which is faster array or object?

The short version: Arrays are mostly faster than objects.

How do you check if an object has a key in JavaScript?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.

What is object keys in JavaScript?

Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.


1 Answers

The V8 design docs imply lookups will be at least this fast, if not faster:

Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.

To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes. [...] In V8, an object changes its hidden class when a new property is added.

It sounds like adding a new key might be slightly slower, though, due to the hidden class creation.

like image 196
Domenic Avatar answered Sep 24 '22 23:09

Domenic