What's the big O for JavaScript's array when used as a hash?

前端 未结 2 955
抹茶落季
抹茶落季 2020-12-05 11:20

What\'s the big O for JavaScript\'s array access when used as a hash?

For example,

var x= [];
for(var i=0; i<100000; i++){
   x[i.toString()+\'a\'         


        
2条回答
  •  余生分开走
    2020-12-05 12:04

    First and foremost Arrays are in fact hashes. Always. That's why x[5] === x["5"]:

    var x = [];
    x[5] = 10;
    alert( x[5] === x["5"] ); // true
    

    Objects are hashes and Arrays are just special objects. If you want to use general hashes go for Objects. "Associative arrays" in Javascript are Objects. Arrays are for numerically indexed data. Arrays have a length property and Array-like methods like push, pop, sort, etc. which makes no sense to be used on hashes.

    As for the big O for searching in Objects: it's implementation dependent.

    Probably the 2 best things you can do to:

    1. Check the source code of some browser implementations

    2. Do some benchmark for big n and make your conclusion


    The related part of the language specification:

    4.3.3 object

    An object is a collection of properties and has a single prototype object.

    8.6.2 Object Internal Properties and Methods

    Array objects have a slightly different implementation of the [[DefineOwnProperty]] internal method. Array objects give special treatment to a certain class of property names.

提交回复
热议问题