Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under the hood, are Javascript objects hash tables? [duplicate]

I was wondering about how Objects are implemented under the hood in Javascript engines (V8, Spidermonkey, etc). Are they really just Hash Tables? If so, how do they handle collisions?

like image 570
Newtang Avatar asked Apr 21 '12 06:04

Newtang


People also ask

Are JavaScript objects hash tables?

A JavaScript Object is an example of a Hash Table because data is represented a key/value pairs. A hashing function can be used to map the key to an index by taking an input of any size and returning a hash code identifier of a fixed size.

Are JavaScript objects hash maps?

While JavaScript doesn't have a native Hashtable class, it does have native Objects and Hashmaps(Map) that offer similar functionality when it comes to organizing key/value pairs.

What is hash tables in JavaScript?

Hash Tables are a data structure that allow you to create a list of paired values. You can then retrieve a certain value by using the key for that value, which you put into the table beforehand.

What is Hash Table data structure?

In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values.


1 Answers

First of all, the answer is probably somewhat different for different JS engines. Also, I assume you're specifically asking about the property storage; obviously objects have a bunch of other state too (prototype chain link being an obvious one).

In the case of Spidermonkey, objects basically have a linked list of (propname, information about property) pairs, until they have too many properties, when I believe they still keep the linked list (because order matters for properties in JS in practice) but add an out-of-band hashtable that maps property names to entries in the linked list.

There may also be other reasons for the switch to the hashtable; the details haven't exactly been fixed over time and are likely subject to change in the future.

The linked lists and hashtables are actually shared across objects; as long as two objects have the same property names and corresponding property information (which does NOT include the value, for properties with a stored value) and the properties were set in the same order, they're able to share the property linked list.

The actual property values, when those need to be stored, are stored in an array in the object (or more precisely, two arrays; one allocated inline with the object, whose size is fixed at object-creation time, one dynamically allocated and resized as needed for properties that are added later).

like image 139
Boris Zbarsky Avatar answered Sep 28 '22 10:09

Boris Zbarsky