深拷贝(clone)是 Java 开发过程中经常遇到问题,有人用 IO 流、有人用 JSON 序列化、有人循环拷贝属性等等,网上文章都能实现功能。
问题:
clone 属于计算操作,消耗 CPU 如果速度慢(高并发场景几十毫秒也是非常慢的)会导致程序卡顿,QPS 降低。网上解决方案都没有提到性能问题,我实际使用后对性能进行了优化,最后推荐 FastClone。
FastClone 介绍
FastClone 是一款非常好用,支持大部分场景深克隆和浅克隆的工具。被推荐的不多,被埋没了。
<dependency>
<groupId>com.github.bruce-cloud</groupId>
<artifactId>fastclone</artifactId>
<version>1.0.RELEASE</version>
</dependency>
用法:
// 深克隆list
FastClone fastClone = new FastClone();
List<T> clone = fastClone.clone(src);
// 深克隆list
FastClone fastClone = new FastClone();
List<T> clone = fastClone.cloneShallow(src);
性能对比
我们项目中用了三种方式对大对象进行深克隆对比 clone:
1. 使用 IO 流写入再读取出来,平均耗时 52ms,也就是会占用 52ms 的 CPU。
public static <T> List <T> deepCopy(List <T> src) {
try {
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteout);
out.writeObject(src);
ByteArrayInputStream bytein = new ByteArrayInputStream(byteout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bytein);
@SuppressWarnings("unchecked")
List < T > dest = (List < T > ) in .readObject();
return dest;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
2. 使用阿里巴巴 fastjson 反序列化先转 JSON 再转对象,平均耗时 65ms,也就是会占用 65ms 的 CPU。
String jsonString = JSON.toJSONString(arrayList);
List < Symbol > configCoinSymbols = JSON.parseArray(jsonString, Symbol.class);
3. 使用 FastClone 反序列化平均耗时 3.4ms,也就是会占用 3.4ms 的 CPU。比其他方式快了将近 20 倍。不过 FastClone 有个缺点,就是不支持 ConcurrentHashMap,其他主流集合都支持。
结论
复杂对象使用其他方式深克隆,会导致 CPU 飙升,QPS下降,接口响应超时等情况。FastClone 性能方面非常好。blog.csdn.net/zjy_love_java/article/details/119465427