简体   繁体   中英

Memory management technique in JavaScript

TL;DR -- What is the difference between these two methods of returning values, from the perspective of memory management? They are being managed within a game loop, and are modified thousands of times a second.

 return { x: x1 + x2, y: y1 + y2, z: z1 + z2 } // VS predeclared.x = x1 + x2; predeclared.y = y1 + x2; predeclared.z = z1 + x2; return predeclared; 

Thanks for any insight!

Some context... In webGL / three.js programs in certain circumstances it is beneficial to pre-declare a dummy reference that will be used to temporarily hold an object every frame instead of creating a new object to assist with garbage collection. I'm pretty sure this is a common practice but just in case it isn't it looks like this:

 let mesh; while( true ) { mesh = getNewMeshFrame( time ); renderStuff( mesh ); } 

I am unsure about the correct technique to be used in a situation like the following.

 // With just ONE predeclared object and an object literal in the return statement function box() { let box = { x: 0, y: 0 }; this.transform = function( addX, addY ) { return { x: box.x + addX, y: box.y + addY }; } } // OR, with TWO predeclared objects function box() { let box = { x: 0, y: 0 }; let transformed = { x: 0, y: 0 }; this.transform = function( addX, addY ) { transformed.x = box.x + addX; transformed.y = box.y + addY; return transformed; } } 

I hope it's clear that the box object is static and must not change (it is a much more complex object IRL), so I need to keep it separate from its transform. Thank you!

The version that returns the object literal will allocate a new object every time transform() is called. These will accumulate in memory over time, and eventually garbage collection will be necessary to remove the ones that are no longer in use.

The version with the predeclared variable returns a reference to the same object every time it's called. So there should be less memory accumulation, and less need for garbage collection. However, this means that if you assign multiple calls to different variables, they're all references to the same object, which is getting modified in place.

b = new box();
t1 = b.transform(1, 2);
t2 = b.transform(3, 4);

With the first version, t1 and t2 are different objects:

t1 = {x: 1, y: 2}
t2 = {x: 3, y: 4}

With the second version they're the same object:

t1 = t2 = {x: 3, y: 4}

If this isn't a problem with the rest of the program, the second version should be significantly more memory efficient if you call transform() many times on the same box.

There's no sharing between different boxes, though.

b1 = new box();
b2 = new box();

In both versions there's no conflict between b1.transform() and b2.transform() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM