Why garbage collection? Why not compilers auto-insert free() instead? -


rather running garbage-detection periodically @ run time, why don't make compilers automatically insert free() @ appropriate places? way, pay price once @ compile-time.

the compiler knows places variable goes out of scope or gets reassigned different object. so, can find out if object no longer reachable, , insert free() automatically there.

can't it? why?

if it's because of multithreading, can single-threaded/green-threaded languages then?

the compiler knows places variable goes out of scope or gets reassigned different object.

sure - variables. not clear variables - clear memory pointing to. , because variable went out of scope, not mean memory pointed no longer reachable.

for example:

y = ... {   x = new x();   if (todayistuesday()) {     y = x;   } } // x went out of scope 

you can't make compile-time decision whether memory pointed x should freed @ last line of segment, because depends on day of week when code ran.

so solve this, decision must delegated run-time, inserting proper logic, e.g.:

y* y = ... {   x* mem = new x();   x* x = mem;   markpointer(&x, mem);   if (todayistuesday()) {     y = x;     markpointer(&y, mem);   }   marknolongerpointer(&x, mem); } // x went out of scope 

with marknolongerpointer() clearing memory given 2nd argument if internally-maintained data structure told x reference memory... in other words, crude starting point reference-counting logic.

compilers can add such reference-counting logic compiled code, , do, others mentioned, reference counting has disadvantages: high overhead, problem of cycles, plus can cause significant pauses @ inconvenient times, when reference root of large data structure goes out of scope. there ways address of these disadvantages, though, that's out of scope answer :-)


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -