I have benchmarked two methods:
Access array items
var object = [10, 15, 20];
var x = object[0];
var y = object[1];
var z = object[2];
and Access object properties
var object = {
x: 10,
y: 15,
z: 20
};
var x = object.x;
var y = object.y;
var z = object.z;
I expected the access to array items to be much faster, since there's no property name resolution involved.
However, to my surprise, accessing object properties was roughly 30% faster across all browsers.
[URL to benchmark]
That benchmark results made me confused. For what reason should the former method be so much slower than the latter?
Objects will be used when we need fast access, insertion and removal of an element as objects are comparatively much faster than the arrays in case of insertion and removal.
The short version: Arrays are mostly faster than objects.
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.
Generally it is faster to use object key value pairs when you have large amounts of data. For small datasets, arrays can be faster.
You have included the creation of the object and the array in the test. If you put that in the initialisation code, the difference becomes very small:
http://jsperf.com/object-properties-and-array-items/2
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