Variables in memory

Hi there,
I have a perhaps trivial curiosity but I haven't found any answers anywhere

let x = "Djokovic";
let x = "Sinner";

now, the value of "x" is "Sinner" and the previous value "Djokovic" is no longer reachable, but the question is: in fact the value "Djokovic" is completely released and therefore available to be rewritten or it still exists and is it in some "blocked" mode until the end of the program? In the latter case wouldn't it be a waste of memory?

Thx, best regards.

The two xs are two different variables, they just share the same name. The compiler is able to reuse the memory of a variable after it is no longer used, indipendently from how they are named.

Ok, thx.

Specifically in case of string literals — they are never released. They're compiled into the executable and stay in memory for entire duration of the program.

For Copy types stored locally in variables (like numbers), this is up to the optimizer what happens. They can be eliminated entirely if they're not used, created only where they're used, or folded into other expressions.

For types with Drop destruction follows a strict set of rules, and generally that means they're destroyed in the reverse order of being defined. Names don't affect that in any way, even if the names overlap/shadow each other.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.