深拷贝(clone)最佳实践 -- 考虑拷贝消耗的cpu和拷贝速度

深拷贝(clone)是java开发过程中经常遇到问题,有人用io流、有人用json序列化、有人循环拷贝属性等等,网上文章都能实现功能。
问题:
clone是计算操作,消耗cpu如果速度慢(高并发场景几十ms也是非常慢的)会导致程序卡顿,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);

在这里插入图片描述
2. 使用FastClone反序列化
平均耗时3.4ms,也就是会占用3.4ms的cpu。比其他方式快了将近20倍。
有个缺点,就是不支持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性能方面非常好。


版权声明:本文为zjy_love_java原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。