程序里到底需要不需要手动调用System.gc()
最近做的项目,同事喜欢在很多类里面加上一个release()之类的方法,并且在最后会调用一次System.gc(),说是这样可以有效的释放资源.在实际测试中,调用System.gc()的确可以回收一部分内存.但是,这个时候通常程序会明显感觉卡一下.到底应不应该手动调用System.gc()呢?我上网查了很多资料,其中一份是诺基亚论坛的<<Known Issues In The Nokia 6600 MIDP 2.0 Implementation>>,开头就是关于GC的:
Description:
Calling the System.gc() method results in extreme slowness and jamming. In Monty 1.0 VM, garbage collection is different and every time System.gc is called, the entire memory is really cleared. This is an extremely slow process!
Solution:
Do not call the System.gc method at all, or call the System.gc() garbage collecting method only in non-time-critical situations, such as screen transitions, state transitions, pause states, etc. If the System.gc() method is used, it is recommended to add a short delay (~20-50 ms) after the method call to ensure the sufficient time for the garbage collection, as in the following example:
System.gc();Thread.sleep(delay); //delay = 20-50 ms
x=null;