Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it always faster to access object properties than array items? [closed]

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.

Chart[URL to benchmark]

That benchmark results made me confused. For what reason should the former method be so much slower than the latter?

like image 455
caiosm1005 Avatar asked Mar 30 '13 22:03

caiosm1005


People also ask

Why is object faster than array?

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.

Which is faster object or array?

The short version: Arrays are mostly faster than objects.

Why is it better to work with objects instead of arrays to store a collection of records?

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.

Which is faster array or object in JS?

Generally it is faster to use object key value pairs when you have large amounts of data. For small datasets, arrays can be faster.


1 Answers

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

like image 90
Guffa Avatar answered Nov 15 '22 15:11

Guffa