Performance issues with maintaining array reference

Why is v1 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 realized that since I keep the reference to the new object in 'ref', simply assigning that link to an array element is about as fast as assigning a literal value, but it turns out that the link assignment is much slower. Can someone shed some light on this? Anything I can do to improve performance here on V1?

Violin:

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

+6
source share
1 answer

just assigning a reference to an element in an array is about as fast as assigning a literal

Yes, basically it is 1 . However, highlighting an object probably matters here.
In V2, ref is allocated only once and is repeatedly overwritten, it can be allocated on the stack not on the heap, and deleting dead code can even completely optimize it.
In V1, ref must be allocated on the heap and re-in the new location, since all different instances are accessible from pcs .

V1 just consumes more memory than V21. However, due to your very small array, the difference is negligible. If you use really big, you can notice the difference: http://jsperf.com/array-reference-assignment/3

[1]: Well, for some reason, not really . But I can’t explain it, except that garbage collection is different when using memory memory

+3
source

Source: https://habr.com/ru/post/987061/


All Articles