1. singleton延时初始化
class Singleton { private static Singleton _instance = null; public synchronized Singleton getInstance() { if(_instance == null) { _instance = new Singleton(); } return _instance; } }
上述代码加入synchronized性能会降低,可以采用内嵌class的方式来优化掉这个不必要的synchronized关键字
class Singleton { static class Holder { private static Singleton _instance = new Singleton(); } public synchronized Singleton getInstance() { return Holder._instance; } }
2. 局部变量的GC 回收。只有再局部变量表失效后才会被回收,例如
public static void test1() { { byte b = new byte[6*1024*1024]; } System.gc(); }
上述代码的full gc并不能有效回收临时变量b,因为这种情况下b仍然在局部变量表中(JDK7仍然如此?),作为安全考虑,应养成习惯将此时的b使用完后置为null,确保GC回收。(否则要么等函数执行完,要么之后新定义的临时变量重用了b所在的entry才有机会被GC)。
原文:http://www.cnblogs.com/perfectbug/p/3592066.html