Javascript字典性能问题 [英] Javascript dictionary performance question

查看:118
本文介绍了Javascript字典性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有以下javascript词典

Right now I have the following javascript dictionary

var a = {};
a['SVG343'] = 1942;
a['UAL534'] = 2153;

右边的数字代表时间,键是唯一的ID。我想让id成为键,因为它们是独一无二的。我的问题是给了一个时间找到相应的id。我怎么做这个是通过字典中的每个条目,直到我找到正确的时间并使用当前的密钥来获取id。

Those numbers on the right represent times, and the keys are unique ids. I wanted to make the ids the keys since they are unique. My problem is given a time find the corresponding id. How was I going to do this was go through each entry in the dictionary until I find the correct time and use the current key to get the id.

但是我担心性能,我的问题是,字典中的每个条目(O(n))是否明显慢于其他任何方法?

However I'm worried about performance, my question is, does going through each entry in the dictionary (O(n)) significantly slower than any other method?

推荐答案

您可以根据时间构建索引:

You could build an index from the times:

var indexByTimes = {};
for (var prop in a) {
    if (a.hasOwnProperty(prop)) {
        indexByTimes[a[prop]] = prop;
    }
}

对于多个时间值,请使用数组ID:

And for multiple time values, use an array for the IDs:

for (var prop in a) {
    if (a.hasOwnProperty(prop)) {
        if (indexByTimes.hasOwnProperty(a[prop])) {
            indexByTimes[a[prop]].push(prop);
        } else {
            indexByTimes[a[prop]] = [prop];
        }
    }
}

然后您可以访问所有ID对应于1942年的时间,其中<​​code> indexByTimes ['1942'] 在O(1)中。

Then you can access all IDs corresponding to the time 1942 with indexByTimes['1942'] in O(1).

这篇关于Javascript字典性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆