Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance issues with saving object reference to array

Why is v1 so much slower than v2?

v1 --

var foo = function (a,b,c) { 
   this.a=a; this.b=b; this.c=c; 
}
var pcs = new Array(32);
for (var n=32; n--;) {
    ref = new foo(1,2,3)
    pcs[n] = ref;    //*****
}

v2 --

var foo = function (a,b,c) { 
   this.a=a; this.b=b; this.c=c; 
}
var pcs = new Array(32);
for (var n=32; n--;) {
    ref = new foo(1,2,3)
    pcs[n] = 1;    //*****
}

I figured that since I'm holding a reference to the new object in 'ref', that simply assigning that reference to an element in the array would be about as fast as assigning a literal value, but it turns out that assigning the reference is considerably slower. Can anyone shed some light on this? Anything I can do to improve the performance here on V1?

Fiddle:

http://jsfiddle.net/a0kw9rL1/1/

like image 303
A Moore Avatar asked May 12 '15 14:05

A Moore


People also ask

Why is it usually 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 objects?

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 more efficient than arrays?

The short version: Arrays are mostly faster than objects.

Are arrays fast in JS?

JavaScript Arrays are great when you only have a few items, but when you have a large amount of data or want to do complex transformations with lots of map , filter , and reduce method calls, you'll see a significant slowdown in performance using Array.


1 Answers

simply assigning that reference to an element in the array would be about as fast as assigning a literal value

Yes, it basically is1. However, allocating an object probably makes the difference here.
In V2, ref is only allocated once and repeatedly overwritten, it might be allocated on the stack not on the heap, and dead code elimination might even completely optimise it away.
In V1, ref needs to be allocated on the heap, and repeatedly in a new location, as all the different instances are accessible from pcs.

V1 is just eating more memory than V21. However, due to your very small array, the difference is neglible. If you use really large one, you can spot the difference: http://jsperf.com/array-reference-assignment/3

[1]: Well, for some reason not really. But I can't explain that, except garbage collection is different when you profile memory usage

like image 141
Bergi Avatar answered Oct 17 '22 05:10

Bergi