JavaScript & Hashtable

JavaScript doesn’t come with a native Hashtable object.

Yet, In Javascript, one can use any object as an associative array, similar to a Hashtable structure.

Since one can add to an object any arbitrary property on the fly. It turns out that any object is just a set of key/value pairs.

The only constraint  is that the key must be String.


var myStrMap = new Object(); //init an object

myStrMap ["key"] = value; //put a value

var val = myStrMap ["key"] ; // get a value

Notice that if one would use non-string object as a key, JavaScript will translate it to string (utilizing the toString() function),

This can cause serious problems since some different objects might return the same toString() value..

Moreover all objects that don’t implement the toString() function will return the same value.. (mostly “[Object object]”)

In order to use non-string object as a key one could do one of the following:

  • Implement hash(myObject) function
  • Implement myObj.toString() function, bare in mind toString() might be needed for other stuff..
  • Use or develop hashtable library for javascript (e.g. )

If you are using Chrome/Chrome Frame/NodeJS and more, it means that you are using Google’s JavaScript Virtual Machine,V8, behined the scene

Specifically V8 doesn’t implement Object properties access as hashtable, it actually implement it in a better way (performance wise)

So how does it work? “V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes” – that make the access to properties almost as fast as accessing properties of Java/C++ objects.

Why? because in fixed class each property can be found on a specific fixed offset location of the memory..

So in general accessing property of an object in V8 is faster than Hashtable..which mean that if one implements Hashtable (string keys) utilizing the approche, he/she will mostly get better performance than utilizing an Hashtable in Java where Hashtable come out of the box

More info can be found here:

The good news is that the next JavaScript version will probably ship with a native map object as suggested on ECMAScript – harmony 


1 thought on “JavaScript & Hashtable

  1. Pingback: How I wrote the world’s fastest JavaScript memoization library | Webammer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s