JavaScript中的数组与对象效率

时间:2013-06-25 10:34:55

标签: javascript performance

我有一个可能有数千个物体的模型。我想知道什么是最有效的存储方式和一旦我拥有它的id后检索单个对象。 id是长号。

所以这些是我想到的两个选项。在选项1中,它是一个带有递增索引的简单数组。在选项2中,它是一个关联数组,也许是一个对象,如果它有所不同。我的问题是哪一个更有效率,当我主要需要检索单个对象时,有时还会遍历它们并进行排序。

具有非关联数组的选项一:

var a = [{id: 29938, name: 'name1'},
         {id: 32994, name: 'name1'}];
function getObject(id) {
    for (var i=0; i < a.length; i++) {
        if (a[i].id == id) 
            return a[i];
    }
}

带关联数组的选项二:

var a = [];  // maybe {} makes a difference?
a[29938] = {id: 29938, name: 'name1'};
a[32994] = {id: 32994, name: 'name1'};
function getObject(id) {
    return a[id];
}

更新

好的,我知道在第二个选项中使用数组是不可能的。因此第二个选项的声明行应该是:var a = {};,唯一的问题是:在检索具有给定id的对象时表现更好:数组或id为关键字的对象。

而且,如果我必须多次对列表进行排序,答案是否会改变?

9 个答案:

答案 0 :(得分:128)

简短版:数组大多比对象快。但是没有100%正确的解决方案。

2017年更新 - 测试和结果

var a1 = [{id: 29938, name: 'name1'}, {id: 32994, name: 'name1'}];

var a2 = [];
a2[29938] = {id: 29938, name: 'name1'};
a2[32994] = {id: 32994, name: 'name1'};

var o = {};
o['29938'] = {id: 29938, name: 'name1'};
o['32994'] = {id: 32994, name: 'name1'};

for (var f = 0; f < 2000; f++) {
    var newNo = Math.floor(Math.random()*60000+10000);
    if (!o[newNo.toString()]) o[newNo.toString()] = {id: newNo, name: 'test'};
    if (!a2[newNo]) a2[newNo] = {id: newNo, name: 'test' };
    a1.push({id: newNo, name: 'test'});
}

test setup test results

原帖 - 解释

你的问题有一些误解。

Javascript中没有关联数组。只有数组和对象。

这些是数组:

var a1 = [1, 2, 3];
var a2 = ["a", "b", "c"];
var a3 = [];
a3[0] = "a";
a3[1] = "b";
a3[2] = "c";

这也是一个数组:

var a3 = [];
a3[29938] = "a";
a3[32994] = "b";

它基本上是一个带孔的数组,因为每个数组都有连续的索引。它比没有孔的阵列慢。但是手动遍历数组甚至更慢(大多数情况下)。

这是一个对象:

var a3 = {};
a3[29938] = "a";
a3[32994] = "b";

以下是三种可能性的性能测试:

Lookup Array vs Holey Array vs Object Performance Test

在Smashing Magazine上关于这些主题的精彩读物:Writing fast memory efficient JavaScript

答案 1 :(得分:21)

这根本不是一个性能问题,因为数组和对象的工作方式非常不同(或至少应该如此)。数组具有连续索引0..n,而对象将任意键映射到任意值。如果想要提供特定密钥,则唯一的选择是对象。如果您不关心键,那就是数组。

如果您尝试在阵列上设置任意(数字)键,那么您确实有性能损失,因为在行为上,数组将填充其间的所有索引:

> foo = [];
  []
> foo[100] = 'a';
  "a"
> foo
  [undefined, undefined, undefined, ..., "a"]

(请注意,数组实际不包含99个undefined值,但它会以这种方式运行,因为您[应该] 迭代< / em>某个时刻的数组。)

这两个选项的文字应该非常清楚如何使用它们:

var arr = ['foo', 'bar', 'baz'];     // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature

答案 2 :(得分:11)

使用ES6,最高效的方法是使用Map。

var myMap = new Map();

myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });

myMap.get(1);
myMap.get(2);

您现在可以使用垫片(https://github.com/es-shims/es6-shim)来使用ES6功能。

性能会因浏览器和方案而异。但这里有一个Map表现最佳的例子:https://jsperf.com/es6-map-vs-object-properties/2

REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

答案 3 :(得分:4)

如果您知道ul.nav a:hover, ul.nav a:focus, ul.nav a.active { background-color: #FDCBA3;} ,则在 NodeJS 中,与ID相比,数组的循环速度非常慢。

object[ID]

结果:

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

即使搜索ID是数组/对象中的第一个:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

答案 4 :(得分:3)

我试图从字面上把它带到下一个维度。

给定一个二维数组,其中x和y轴总是相同的长度,它更快:

a)通过创建一个二维数组并查找第一个索引,然后查找第二个索引来查找单元格,即:

var arr=[][]    
var cell=[x][y]    

b)使用x和y坐标的字符串表示创建一个对象,然后对该obj进行单个查找,即:

var obj={}    
var cell = obj['x,y']    

结果:
事实证明,在数组上进行两次数字索引查找比在对象上进行一次属性查找要快得多。

此处的结果:

http://jsperf.com/arr-vs-obj-lookup-2

答案 5 :(得分:2)

取决于使用情况。如果是查找对象的情况非常快。

这是一个测试数组和对象查找性能的Plunker示例。

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

你会看到; 在 5.000 长度数组集合中查找 5.000 项目,接管3000 milisecons

但是,在对象中查找 5.000 项目 5.000 属性时,只需23 milisecons

同样使对象树没有太大的区别

答案 6 :(得分:0)

我遇到了类似的问题,即我需要存储来自x个项目的事件源中的实时烛台。我可以将它们存储在一个对象中,其中每个蜡烛的时间戳记将作为键,而蜡烛本身将作为值。另一种可能性是,我可以将其存储在一个数组中,其中每个项目都是蜡烛本身。实时蜡烛的一个问题是,它们始终在同一时间戳上发送更新,其中最新更新保存了最新数据,因此您可以更新现有项目或添加新项目。因此,这是一个很好的基准,尝试将所有3种可能性结合在一起。以下解决方案中的阵列平均至少快4倍。随意玩

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor(Date.now() / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values
    console.clear()

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume
    });



}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];
        }
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {
        candles.push(candle);
    }

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle
    }

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]


    console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}

结论 极限是10个

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

答案 7 :(得分:0)

如果您有一个排序的数组,则可以进行二进制搜索,这比对象查找要快得多,您可以在这里看到我的答案:
How to search faster in a sorted Array using Javascript

答案 8 :(得分:0)

  1. 索引字段(带有数字键的字段)作为神圣数组存储在对象内部。因此查找时间为O(1)

  2. 与查找数组相同,为O(1)

  3. 遍历对象数组并根据提供的对象测试其ID是O(n)操作。