0

Assuming the following in the global window scope:

var myvar = "initial value";
//some other code
myvar = "new value";

Is the old value destroyed from memory as soon as the new value is assigned? Of will it be Garbage Collected? My profiling tests suggest the memory is freed right away.

And same question when declared in a function scope.

var myfunct = function(){
  var myvar = "initial value";    
  //some other code
  myvar = "new value";
}

PS: No need to answer on the garbage collection in general. I already have an understanding how that works... I am only after the memory re-assignment aspect for this question. I know that global variables never get collected. But I am curious if the memory reassignment also get treated differently at the root.

2
  • 4
    That is an implementation detail that is up to each browser, it has nothing to do with javascript (ECMAScript) per se. Someone involved in the detail of browser design may know, but they are unlikely to visit here. Commented Dec 23, 2013 at 9:35
  • @RobG I am obviously well aware of such observations. GC collection methods may vary, but I wouldn't think that what gets released right away is much different from engine to engine for this context... Commented Dec 23, 2013 at 9:46

1 Answer 1

1

Since strings in javascript are immutable and string variables are references, there is no "memory reassignment" taking place.

How and when the dead value is freed is entirely up to the GC. AFAIK the standards place few restrictions on the implementations in this regard, and I don't believe there is a concept such as "released right away". Therefore it is hard to say anything general, as noted by RobG

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

1 Comment

Ok. I actually see the GC happening in my Chrome test now (with a var of 500Kb). I think it was initially skipping it, due to the fact that the overwriting value was identical or nearly identical. Thanks

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.