Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a deep object slow in JavaScript? If so how much

Simple question: is there a merit of using a shallow object over a deeper one? When I write a code, I tend to use a deep object just so it is easy to understand and classify. But I am wondering if this custom is making my code slower.

I have done a test but I have no idea if I am doing it correctly.

//building necessary objects
var a = {};
var b;
b = a;
for (var i = 0; i < 100; i++) {
  b["a"] = {};
  b = b["a"];
}
var c = {};

//objects used
//a.a.a. ..(101 "a"s).. .a === {}
//c === {}

//1st test: shallow
var d;
var start = performance.now();
for (var i = 0; i < 1000000000; i++) {
  d = c;
  d = null;
}
var end = performance.now();
console.log('Shallow: ' + (end - start));

//2nd test: deeper
var e;
var start = performance.now();
for (var i = 0; i < 1000000000; i++) {
  e = a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a;
  e = null;
}
var end = performance.now();
console.log('Deeper: ' + (end - start));

the result(ms):

shallow 3229 3304 3246 3253 3277
deep    3375 3343 3247 3193 3248

The test times for the deep object is not slow, but sometimes even faster than the shallow one. Despite the result, I am not confident enough to conclude that they are the same speed. Is there any difference between two of them?

like image 355
Y. Yoshii Avatar asked Sep 05 '17 04:09

Y. Yoshii


People also ask

How fast is object values in JavaScript?

Conclusion. It turns out that Object. values is about 3.2 times faster than Object.

Are objects faster than arrays JavaScript?

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.

Are objects slower than arrays?

The short version: Arrays are mostly faster than objects.

Why objects are better than arrays JavaScript?

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.


Video Answer


1 Answers

It is an optimisation in the js engine to access objects directly and allow for deep objects to be cashed in a variable which takes less time to reach. So it is faster to access them without having to go through the chain. For example:

var a={a:{a:{}}}
var b=a.a.a
var c=b
// is faster than 
var c=a.a.a

For more information read this: JavaScript Performance: Mutiple variables or one object?

like image 69
user7951676 Avatar answered Nov 10 '22 08:11

user7951676