Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
if I declared int a=2 , and it is not used anywhere in the code,does garbage collector will free it
Posted

No! Your example uses value object (as opposed ) which does not have to be collected. More exactly, it could be a stack variable, then it will be removed when the stack frame is removed (say, on method return), and this has nothing to do with allocation or deallocation, or this could be an instance member of some object, so the object will be garbage collected, no matter is your member is used or not.

Besides, as it is pointed out in Solution 2, the variable could be optimized out by a compiler, then it would not exist at all, in first place.

—SA
 
Share this answer
 
Comments
Mehdi Gholam 8-Feb-15 5:45am    
Yes, 5'ed
Frankie-C 8-Feb-15 6:48am    
The removal of this kind of code, at compile time, is called 'dead code removal' and has another important scope related to the preprocessor conditional compile, it removes code that statically (at compile time) lead to a never executed condition.
In the following code the compiler found a clause that will never be satisfied and remove the unusefull code compacting the executable:

if (sizeof(a) < sizeof(b))
.... //do something
else
... //do other things
Because the result of operators sizeof are constants the compiler understand that one of the two parts will never execute, and simply remove it as dead code.
Sergey Alexandrovich Kryukov 8-Feb-15 13:20pm    
Sure. Thank you for useful explanation and example.
—SA
If you build as "release" instead of "debug", a variable that is declared but never used will be optimized on build, and actually not even put into the compiled code.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Feb-15 4:57am    
Not that this answer is wrong, but it is very confused. The inquirer confuses totally unrelated optimization and garbage collection and needs help to overcome the confusion first, otherwise your information won't help.
Please see my Solution 3.
—SA
Yes. It will be freed when the instance is not in use.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 8-Feb-15 4:57am    
Instance of what? Of the value object? :-)
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900