最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript garbage collection when variable goes out of scope - Stack Overflow

programmeradmin2浏览0评论

Does JavaScript support garbage collection?

For example, if I use:

function sayHello (name){
    var myName = name;
    alert(myName);
}

do I need to use "delete" to delete the myName variable or I just ignore it?

Does JavaScript support garbage collection?

For example, if I use:

function sayHello (name){
    var myName = name;
    alert(myName);
}

do I need to use "delete" to delete the myName variable or I just ignore it?

Share Improve this question edited Oct 22, 2009 at 14:35 Crescent Fresh 117k27 gold badges157 silver badges140 bronze badges asked Oct 22, 2009 at 13:38 DNB5brimsDNB5brims 30.6k50 gold badges133 silver badges203 bronze badges 3
  • certainly no, CTO: codingforums.com/archive/index.php/t-157637.html – Rakesh Juyal Commented Oct 22, 2009 at 13:44
  • Please retag/retitle: this has nothing to do with optimization. I suggest "JavaScript variable scope" – kdgregory Commented Oct 22, 2009 at 13:49
  • See also this question about the JS GC - stackoverflow.com/questions/864516/… – Kobi Commented Oct 22, 2009 at 13:51
Add a comment  | 

5 Answers 5

Reset to default 7

no.
delete is used to remove properties from objects, not for memory management.

Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.

JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete (per reference linked below).

Where delete may be useful is if you declare variables implicitly, which puts them in global scope:

function foo()
{
    x = "foo";   /* x is in global scope */
    delete x;
}

However, it's a bad practice to define variables implicitly, so always use var and you won't have to care about delete.

For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

You don't need to do anything Ted, no need to delete this variable.

Refer: http://www.codingforums.com/archive/index.php/t-157637.html

As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.

But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.

You may want to read up on scoping in javascript: http://www.webdotdev.com/nvd/content/view/1340/

With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned: http://www.jibbering.com/faq/faq_notes/closures.html

发布评论

评论列表(0)

  1. 暂无评论