JavaScript:关联数组的内存/效率?

Azm*_*sov 5 javascript memory performance associative-array

我正在从关联数组中构建一个树状数据结构.每个键为1-2个字符.钥匙是各自级别的独特之处.根级别上的密钥不超过40个,并且树的每个后续级别上的密钥不超过5个.它可能看起来像这样:

{a:{b:null,c:null},de:{f:{g:null}},h:null,i:null,j:null,k:null}

最初,我认为创建这么多具有​​如此少的键(平均<3)的对象将是低效且内存密集的.在这种情况下,我会像这样实现自己的哈希表:

//Suppose keys is a multi-dimensional array [[key,data],...]
var hash = function(keys){
    var max = keys.length*3, tbl = [];
    //Get key hash value
    var code = function(key){
        return (key.charCodeAt(0)*31)%max;
    }
    //Get key values
    this.get(key){
        //2 character keys actually have a separate hash generation algorithm...
        //we'll ignore them for now
        var map = code(key), i=map;
        //Find the key value
        while(true){
            if (typeof tbl[i] == 'undefined') return false;
            if (code(tbl[i][0]) == map && tbl[i][0] == key) return tbl[i][1];
            else i = (i+1)%max;
        }
    }

    //Instantiate the class
    for (var i=0; i<keys.length; i++){
        var index = code(keys[i][0]);
        while(typeof tbl[index] != 'undefined')
            index = (index+1)%max;
        tbl[index] = keys[i];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我在某处读到JavaScript的数组有时在稀疏填充时被实现为关联数组,这可能会破坏我自己的哈希结构的目的.但我不确定.那么,在内存和速度方面哪个更有效?