面向性能优化的代码调优
代码调优不是为了修复bug,而是对正确的代码进行修改以提高其性能(时间空间复杂度)。
通常是小规模的变化。
Common Sources of Inefficiency
- Object creation
- GC
- 主要围绕以上两点进行优化
- I/O、paging、operators…
设计模式
Singleton Pattern 单例模式
某些类在应用运行期间 只需要一个实例
起源
- Naive: create many objects that represent the same conceptual instance
程序员一般需要对象时就new,导致创建多个object - Better: only create one object and reuse it 更好的选择:强制client只 能创建一个object实例,避免因为new操作和GC所带来的时空性能损 失,也便于复用
优点
- Reduced name space. (The Singleton pattern is an improvement over global variables).
- Controlled access to sole instance
- Class encapsulates code to ensure reuse of the object; no need to burden client
单例模式
lazy load:在需要的时候再new,而非提前构造出来
public class Singleton {
private static final Singleton instance = null;
private Singleton() {...}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
// other operations and data
}
Flyweight Pattern 轻量模式
实现接口,共享轻量类、非共享轻量类
外部数据保存在客户端,客户端自行维护或计算可共享对象的外部特征
客户端根据内部数据设置轻量工厂
Prototype Pattern 原型模式
Prototype pattern refers to creating duplicate object while keeping performance, providing one of the best ways to create an object
通过克隆而非new来创建object
直接new的时空代价高,尤其是需要 与外部I/O、网络、数据库打交道时候
实现Cloneable接口
protected Object.clone()是浅拷贝
浅拷贝
- 只进行赋值,是引用拷贝
- 使用一个已知实例的成员变量对新创建实例的成 员变量逐个赋值
深拷贝
- 对象拷贝
- 类的拷贝方法不仅要复制对象的所有非引用成员变量值(简单数据类型),还要为引用类型(对象)的成员变量创建新的实例,并且初始化为原对象的值。
// 数据成员都是基本数据类型时
// 直接返回super.clone
@Override
protected Object clone(){
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
// 数据成员有引用类型时
// 引用类型也要实现cloneable接口
// 得到super.clone对象后
// 还需set(xx.clone())显式设置数据成员
@Override
protected Object clone(){
Object clone = null;
try {
clone = super.clone();
Address a=((Person)clone).getAddress();
((Person)clone).setAddress((Address) a.clone());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
注意点
- x.clone() != x
- x.clone().getClass() == x.getClass()
- x.clone().equals(x)==false 如果不重写equals()和hashCode()方法
Object Pool Pattern 对象池模式
Canonicalizing Objects
Avoiding Garbage Collection
Object Initialization
Code Tuning for Strings
字符串常量池,在heap中单独开辟的区域
Use the string concatenation operator to create Strings at compile time
Use StringBuffers to create Strings at runtime.
Manipulate characters in char arrays rather than using String and StringBuffer manipulation.