The short version: Arrays are mostly faster than objects.
Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.
No. 1. Arrays are best to use when the elements are numbers. objects are best to use when the elements strings (text).
Think about what your particular data represents: If it's a single entity with named properties, you want an object. If it's a group of entities of the same type/shape, or if order matters, you likely want an array.
The short version: Arrays are mostly faster than objects. But there is no 100% correct solution.
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'});
}
There are some misconceptions in your question.
These are arrays:
var a1 = [1, 2, 3];
var a2 = ["a", "b", "c"];
var a3 = [];
a3[0] = "a";
a3[1] = "b";
a3[2] = "c";
This is an array, too:
var a3 = [];
a3[29938] = "a";
a3[32994] = "b";
It's basically an array with holes in it, because every array does have continous indexing. It's slower than arrays without holes. But iterating manually through the array is even slower (mostly).
This is an object:
var a3 = {};
a3[29938] = "a";
a3[32994] = "b";
Here is a performance test of three possibilities:
An excellent read about these topics at Smashing Magazine: Writing fast memory efficient JavaScript
It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n
, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.
If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:
> foo = [];
[]
> foo[100] = 'a';
"a"
> foo
[undefined, undefined, undefined, ..., "a"]
(Note that the array does not actually contain 99 undefined
values, but it will behave this way since you're [supposed to be] iterating the array at some point.)
The literals for both options should make it very clear how they can be used:
var arr = ['foo', 'bar', 'baz']; // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature
With ES6 the most performant way would be to use a Map.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
You can use ES6 features today using a shim (https://github.com/es-shims/es6-shim).
Performance will vary depending on the browser and scenario. But here is one example where Map
is most performant: https://jsperf.com/es6-map-vs-object-properties/2
REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
In NodeJS if you know the ID
, the looping through the array is very slow compared to 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');
And the results:
Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms
Even if the seeking ID is the first one in the array/object:
Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With