Android: Is there any advantage of settings refere

2019-08-09 06:37发布

问题:

Since the garbage collector uses a Mark-Sweep algorithm:

The actual GC is done using a Mark-Sweep algorithm. This is done using a bitvector to track which objects are reachable initially marking root objects as reachable. Then the GC does a sweep over the objects in the heap in address order marking. For each reachable object it sweeps over it marks all objects reachable from that object as reachable. If the new object has a lower address it is added to a work queue. After the initial sweep the work queue is

So it will pass by every object that has a reference to the root and every other will be collected is there any case when putting a reference to null on an Activity is useful?

Putting on onDestroy I assume that has no advantage correct? What about putting them as null on onPause (after validating isFinishing) on "heavy" activities. Will it help the resources to get collected sooner?

回答1:

So it will pass by every object that has a reference to the root and every other will be collected is there any case when putting a reference to null on an Activity is useful?

Yes. If its static

Putting on onDestroy I assume that has no advantage correct?

I would say this is negligible and therefore pointless as the Activity will be GC-root-less itself momentarily

...What about putting them as null on onPause on "heavy" activities. Will it help the resources to get collected sooner?

If an object does not have a GC root it is eligible for GC. OnPause happens at some point before onDestroy (depending on the execution case this may be any range of time) ergo yes to the above question.

BUT! You would not want to do this as your activity may come back to the foreground after onPause and your would have to allocate all your 'heavy' objects again - which would most likely end up in a crappy experience for the end-user.



回答2:

By making any object = null we are indirectly telling garbage collection that object is not required to be use ( Making it eligible for garbage collection)