【问题标题】:Javascript dictionary performance questionJavascript字典性能问题
【发布时间】:2011-06-01 15:20:24
【问题描述】:

现在我有以下 javascript 字典

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

右边的数字代表时间,键是唯一的 id。我想让 id 成为键,因为它们是唯一的。我的问题是给一个时间找到对应的id。我将如何做到这一点是遍历字典中的每个条目,直到找到正确的时间并使用当前键来获取 id。

但是我担心性能,我的问题是,遍历字典中的每个条目 (O(n)) 是否比任何其他方法都慢得多?

【问题讨论】:

  • 第一行应该是var a = {};,因为这里没有使用数组
  • 时代也是独一无二的吗?如果不是,如果多个ID具有相同的时间值,你会选择哪个?
  • 时间不唯一,我会得到所有对应那个时间的id

标签: javascript performance search


【解决方案1】:

你可以建立一个时代的索引:

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

对于多个时间值,使用一个数组作为 ID:

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

那么你就可以在 O(1) 中使用indexByTimes['1942'] 访问与时间 1942 对应的所有 ID。

【讨论】:

【解决方案2】:

遍历字典的所有键是O(n)。因此,遍历a.items() 也将是O(n)。但是遍历所有键然后查找值(即for(var key in a) { x += a[key]; })是O(n*log(n))。因此,最好通过 a.items() 进行迭代或仅使用列表

【讨论】:

    猜你喜欢
    • 2012-06-22
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    相关资源
    最近更新 更多