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.

e.g.

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. http://www.timdown.co.uk/jshashtable/ )

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 object.properties 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: http://code.google.com/intl/sv/apis/v8/design.html#prop_access

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

Advertisements

Poll: Which web technology will you choose for your next product/app?(After the Google AppEng Revolution)