java - Is it helpful to set the variable and object to null? -


i optimize code, , have little question. if this:

textview currentconsole = (textview)findviewbyid(r.id.txt_mainactvt_currentconsole); string currentconsolename = currentconsole.gettext().tostring(); currentconsole = null; floatingactionbuttonclickevent(currentconsolename); 

is set objects null way, or useless?

the garbage collector tracks references objects, , when there no pointer object marked deletion. no deleted immediately. when write currentconsole = null; tell gc console object should deleted , on next garbage collection.

to optimize can call system.gc(); trigger collection, gc might chose ignore there no guarantee console object delete after null assignment.

the garbage collection interval calculated in run-time depending on number of objects , frequency of new allocations, best thing can let gc job, in cases best thing.

and null assignments in general, yes useful in rare cases, consider code

void testgcmethod() {     //create big object     verybigobjecttype o = new verybigobjecttype();     //do dometinh o     o.somemethod();      //do takes long time complete doesn't involve o     thread.sleep(1000 * 1000 * 1000); }// end of method meaning o pointer has been freed , big object has been marked deletion. 

so in case (if jit doesn't rearrange code) verybigobjecttype instance kept whole time in memory, developers assign o null collected possible gc

void testgcmethod() {     //create big object     verybigobjecttype o = new verybigobjecttype();     //do dometinh o     o.somemethod();     o=null;       //do takes long time complete doesn't involve o     thread.sleep(1000 * 1000 * 1000); }// end of method meaning o pointer has been freed , big  

this way big object deleted (probably) before thread.sleep , save memory;


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 -