查看原文
其他

深拷贝最佳实践:考虑拷贝消耗的 CPU 和拷贝速度

ImportNew 2023-01-29

(给ImportNew加星标,提高Java技能)


深拷贝(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>

用法:

// 深克隆listFastClone fastClone = new FastClone();List<T> clone = fastClone.clone(src);
// 深克隆listFastClone 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,其他主流集合都支持。

public static < T > List < T > deepCopy(List < T > src) { FastClone fastClone = new FastClone(); try { List < T > clone = fastClone.clone(src); return clone; } catch (Exception e) { log.error("deepCopy 克隆失败", e); throw new ExchangeException("deepCopy 克隆失败"); }}


结论

复杂对象使用其他方式深克隆,会导致 CPU 飙升,QPS下降,接口响应超时等情况。FastClone 性能方面非常好。

转自:鲫鱼哥,

链接:blog.csdn.net/zjy_love_java/article/details/119465427


- EOF -

推荐阅读  点击标题可跳转

1、看一遍就理解:零拷贝详解

2、谈谈 Java 开发中的对象拷贝

3、渐析 Java 的浅拷贝和深拷贝


看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

点赞和在看就是最大的支持❤️


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存