Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array lookup efficiency: associative vs. stored associative?

I've been reading, and they're saying that associative arrays won't give you the same efficiency as arrays. An associative array can look things up in O(N) time, where an array can look things up in O(1).

Here's my question: which one would be more efficient in terms of looking up values quickly and not hogging too much memory?

Associative:

var myVars=new Array(); 
myVars['test1'] = a;
myVars['test2'] = b;
myVars['test3'] = c;
... (up to 200+ values)

echo myVars['test2'];

Stored Associative:

var myVars=new Array(); 
var TEST1 = 1;
var TEST2 = 2;
var TEST3 = 3;
... (up to 200+ values)

myVars[TEST1] = a;
myVars[TEST2] = b;
myVars[TEST3] = c;
... (up to 200+ values)

echo myVars[TEST2];
like image 402
howdoicodethis Avatar asked May 04 '11 19:05

howdoicodethis


1 Answers

First, the first usage of Array is wrong. Although it is possible to do it, it does not mean you should. You are "abusing" the fact that arrays are objects too. This can lead to unexpected behaviour, e.g. although you add 200 values, myVars.length will be 0.

Don't use a JavaScript array as associative array. Use plain objects for that:

var myVars = {}; 
myVars['test1'] = a;
myVars['test2'] = b;
myVars['test3'] = c;

Second, in JavaScript there is no real difference between the two (objects and arrays). Arrays extend objects and add some behaviour, but they are still objects. The elements are stored as properties of the array.

You can find more information in the specification:

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232−1. (...)

So both:

var obj = {'answer': 42};
obj['answer'];

and

var arr = [42];
arr[0];

have the same access time, which is definitely not O(n).

†: It is better to say should have. Apparently this varies in different implementations.


Apart from that, your second example is horrible to maintain. If you assign numbers to variables, why not use the numbers directly?

var myVars = []; 
myVars[0] = a;
myVars[1] = b;
myVars[2] = c;

Update:

More importantly: You have to choose the right data structure for your needs and this is not only determined by the access time of a single element, but also:

  • Are the keys consecutive numbers or arbitrary strings/numbers?
  • Do you have to access all (i.e. loop over all) elements of the collection?

Numerical arrays (arrays) and associative arrays (or hash tables/maps (objects in JS)) provide different solutions for different problems.

like image 126
Felix Kling Avatar answered Oct 08 '22 15:10

Felix Kling