I am working with image processing with canvas.
Users will select 10 photos (normally large-resolution photos) each time, then a script will process these photos before uploading them to a server.
The process will create large arrays and consumes lots of memory. So I am wondering which of the options listed below is the correct way to free memory.
option 1: do nothing, leave GC to handle the memory use
for(int i=0;i<10;i++) {
var bigArray = new Array(20000000);
//do something with bigArray
}
option 2: set to null
for(int i=0;i<10;i++) {
var bigArray = new Array(20000000);
//do something with bigArray
bigArray=null;
}
option 3: set to null after freeing array contents
for(int i=0;i<10;i++) {
var bigArray=new Array(20000000);
//do something with bigArray
bigArray=[];
bigArray=null;
}
option 4: set to null after setting array length to zero
for(int i=0;i<10;i++) {
var bigArray=new Array(20000000);
//do something with bigArray
bigArray.length=0;
bigArray=null;
}
bigArray will get garbage collected completely if all references to it are lost. With:
bigArray = [];
the original reference gets lost, and the array gets garbage collected, bigArray points to a new empty array. With:
bigArray = null;
the reference gets lost too. With
bigArray.length = 0;
the array will loose the reference to all its stored values, just the array itself stays in memory.
Now what you should do (instead of creating a leaking a variable outside of a loop and manually manage its dereferencing):
Just define the scope properly, so that it will automatically gets unreferenced:
for(let i = 0; i < 10; i++) {
let bigArray = new Array(20000000);
//do something with bigArray
//...
// array gets recycled here
}
Sidenote:
Array(20000000) is not a big array until you fill it with actual values.
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