3

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() )); 
2
  • 1
    to test for memory leaks, run it a million times with random inputs, and look at the amount of memory used by the process. It is doesn't go up, you don't have a leak; if it does, you do. Commented Nov 19, 2013 at 4:10
  • Why do you think there is any memory leak? And why are you trying to access t.List() after you set t = undefined? Commented Nov 19, 2013 at 4:11

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.