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/
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.
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.
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.
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
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