Question

using Javascript.

I declare an image variable like so:

var myIMG = new Image();

I load up 100 images like this:

for (var test =0 ; test < 100; test++)
{
     myIMG.src = null;
     myIMG.src = {get new image from server somehow}
}

and this:

for (var test =0 ; test < 100; test++)
{
     myIMG = new Image();
     myIMG.src = {get new image from server somehow}
     myIMG.src = null;
     delete myIMG
}

(code is for testing purposes)

What is the correct way to reduce memory consumption?

Thanks

Was it helpful?

Solution

You might be interested to know that JavaScript doesn't have a local scope for a for loop. It's scoping is based on functions. Hence, you should not redeclare var myImg more than once in a function.

Going back to your code, I would suggest that you only declare one new Image() (i.e. outside the loop), which should be more efficient

var i, myImg = new Image();

for(i = 0; i < 100; i++) {
    myImg.src = getNewSource();
}

The delete property is meant for removing an item from an object. For example:

var myObj = { a: 2, b: 3 };
delete myObj.a;
// myObj will now be { b: 3 }

However, this does not necessary release the memory, but the reference to the item in the object. The memory is claimed back by the JavaScript garbage collector (and you cannot trigger this in your code)

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top