Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript delete object safe for memory leak

this is my code, I do not know if it good for prevent leaking memory ? help and how can I test for leaking memory?

var Test = function () {
        this.ar = [];
        this.List = function () {
            return this.ar;
        }
        this.Add = function (str) {
            this.ar.push(str);
        }
    }

use:

var t = new Test();
        t.Add("One");
        t.Add("Two");
        t.Add("Three");
        alert(JSON.stringify(t.List()));
        t = undefined;
        alert(JSON.stringify(t.List() )); 
like image 316
tanthuc Avatar asked Jul 03 '26 04:07

tanthuc


1 Answers

Setting t to undefined will clear that reference to the object. If there are no other references to that object in your code, then the garbage collector will indeed free up that Test() object. That's how things work in javascript. You don't delete an object, you just clear any references to it. When all references are gone, the object is available for garbage collection.

The actual delete keyword in javascript is used only to remove a property from an object as in delete t.list.

Different browsers have different tools available for keeping track of memory usage. The most universal, blackbox way I know of for a test is to run a cycle over and over again where you assign very large objects (I often use big strings) into your test (to consume noticable amounts of memory) with some sort of setTimeout() in between some number of runs (to let the garbage collector have some cycles) and then just watch the overall memory usage of the browser. As long as the overall memory usage doesn't keep going up and up as you keep doing more and more runs then you must not have a noticeable leak.

Individual browsers may have more comprehensive measuring tools available. Info here for Chrome.

like image 176
jfriend00 Avatar answered Jul 05 '26 18:07

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!