Javascript Array lookup efficiency: associative vs. stored associative?

后端 未结 4 456
逝去的感伤
逝去的感伤 2021-02-04 19:52

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 ar

4条回答
  •  忘掉有多难
    2021-02-04 20:21

    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.

提交回复
热议问题