【问题标题】:using json object with lots of properties instead of arrays使用具有大量属性而不是数组的 json 对象
【发布时间】:2014-11-28 02:57:14
【问题描述】:

而不是数组:

var arrayExample = {
  "lotsOfStuff" : [
    {"id" : "th1", "name" : "thing1", "type": "thing", "moo":"a"},
    {"id" : "th2", "name" : "thing2", "type": "thing", "moo":"z"},
    {"id" : "th3", "name" : "aDifferentThing3", "type": "differentThing", "moo":"m"}
  ] 
}

使用很多属性:

var propertyExample = {
  "lotsOfStuff" : {
    "id1" : {"name" : "thing1", "type" : "thing", "moo" : "a" },
    "id2" : {"name" : "thing2", "type" : "thing", "moo" : "z" },
    "id3" : {"name" : "aDifferentThing3", "type" : "differentThing", "moo" : "m" }
  }
}

仍然可以遍历它们

for(var idx in arrayExample.lotsOfStuff) {
  var thing = lotsOfStuff[idx];
  var id = thing.id;
  ...
}

和

for(var id in propertyExample) {
  var thing = lotsOfStuff[id];
  ...
}

但是您可以通过 id 进行查找,但会以索引位置查找为代价

使用这个数组替代品有什么问题吗? 有很多元素的性能怎么样??

【问题讨论】:

    标签: arrays json properties


    【解决方案1】:

    如果元素的顺序很重要,请使用数组。

    如果需要按 ID 查找,请使用对象。

    如果您需要两者都做,请同时创建一个数组和一个其元素指向相同对象的对象。

    访问对象属性可能比访问数组元素慢,因为它需要散列而不是简单的索引。但是,如果您需要在数组中按 ID 查找,则需要进行线性搜索,如果有很多元素,这将比散列慢得多。对象的性能不应受到元素数量的显着影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 2018-04-15
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多