Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High performance JS map for int-string pairs

I need a high performance map in Javascript (hashmap or whatever) that maps int(s) to string(s). The map would be used to build some sections of the webpage after dom is ready. I know simple javascript object also works like a map but I need to work with best performance.

I would like to initialize the map with all data pairs just at once by appending a string to the webpage while generating the response page from server.

Any ways how to improve performance of javascript map for int- string pairs or are there any implementations for the same ?

--

Using jQuery 1.7

like image 932
Rajat Gupta Avatar asked Oct 25 '12 09:10

Rajat Gupta


1 Answers

Ok, I'll post it here since it's more of an answer:

Use an array. Taken into account that any implementation will have to use js primitives and objects, you'll be hard pressed to find something more performant than that.

Arrays in most (all?) implementations of javascript can be sparse. So array.length will return the index of last element + 1, but in sparse case the array will not have all elements allocated and will use object property semantics to access it's elements (meaning, it's effectively a hashtable with ints as keys).

It basically gives you the behavior you're looking for.

In case of negative ints, use a second array.

In relation to a single statement initialization: you can't do it in general, since it bases itself on implicitly knowing the item index.

What you can do is to append something along the lines:

 var arr = [];

 arr[int1] = val1;
 arr[int2] = val2;
 arr[int3] = val3;
 arr[int4] = val4;
 ...
 arr[intn] = valn;

I mean you have to list (Number, String) pairs somehow anyway.

like image 179
soulcheck Avatar answered Oct 07 '22 17:10

soulcheck