简体   繁体   中英

undersatnding javascript immutable variable and garbage collector

var foo="text";
foo="another text";
console.log(foo); //=>"another text"

I know strings in javascript are immutable. So here var foo points a memory block with the value "text" . After second statement foo points another memory block with the value "another text".

Now what happens to the first value("text") ? will it exist in the memory until the garbage collector pass?

It's up to the implementation. If the JS interpreter isn't sharing common strings, then it may know right away that the original string can be freed when the variable is assigned a new string and it could act right away, but certainly doesn't have to.

If it is sharing common strings among multiple variables, then it may just wait until the garbage collector runs and realizes that nothing has a reference to the string block.

This is implementation dependent and not specified by any standard (nor does it need to be).

What is strings in JavaScript ? An array of characters right ? When you assign var x = 'test'; it allocate a memory address containing the array of characters and a null reference character at it's end. It is for garbage collector. Now you assign x = 'another test', it definitely allocate a new memory address but variable name is same right ? That means the initial pointer for the new string characters array refers to x' first character array index and when you call x it returns the newly assigned value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM