Protostuf序列化

工具对比

JdkSerialize: java内置的序列化能将实现了Serilazable接口的对象进行序列化和反序列化,ObjectOutputStream的writeObject0方法可序列化对象生成字节数组

Protostuf:google开源的protostuf采用更为紧凑的二进制数组,表现更加优异,然后使用protostuff的编译工具生成pojo类

代码实现

导入依赖

xml 复制代码
<dependency>
    <groupId>io.protostuff</groupId>
    <artifactId>protostuff-core</artifactId>
    <version>1.6.0</version>
</dependency>

<dependency>
    <groupId>io.protostuff</groupId>
    <artifactId>protostuff-runtime</artifactId>
    <version>1.6.0</version>
</dependency>

创建工具类

java 复制代码
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

public class ProtostuffUtil {

    /**
     * 序列化
     * @param t
     * @param <T>
     * @return
     */
    public static <T> byte[] serialize(T t){
        Schema schema = RuntimeSchema.getSchema(t.getClass());
        return ProtostuffIOUtil.toByteArray(t,schema,
                LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));

    }

    /**
     * 反序列化
     * @param bytes
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte []bytes,Class<T> c) {
        T t = null;
        try {
            t = c.newInstance();
            Schema schema = RuntimeSchema.getSchema(t.getClass());
            ProtostuffIOUtil.mergeFrom(bytes,t,schema);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }

}

测试

ini 复制代码
/**
 * jdk序列化与protostuff序列化对比
 * @param args
 */
public static void main(String[] args) {
    long start =System.currentTimeMillis();
    for (int i = 0; i <1000000 ; i++) {
        WmNews wmNews =new WmNews();
        JdkSerializeUtil.serialize(wmNews);
    }
    System.out.println(" jdk 花费 "+(System.currentTimeMillis()-start));

    start =System.currentTimeMillis();
    for (int i = 0; i <1000000 ; i++) {
        WmNews wmNews =new WmNews();
        ProtostuffUtil.serialize(wmNews);
    }
    System.out.println(" protostuff 花费 "+(System.currentTimeMillis()-start));
}

运行结果

yaml 复制代码
jdk 花费 3160
protostuff 花费 308
相关推荐
超级小忍8 分钟前
Spring Boot 与 Docker 的完美结合:容器化你的应用
spring boot·后端·docker
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
程序员爱钓鱼3 小时前
Go语言实战案例-读取用户输入并打印
后端·google·go
Livingbody7 小时前
基于【ERNIE-4.5-VL-28B-A3B】模型的图片内容分析系统
后端
你的人类朋友8 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
追逐时光者9 小时前
面试第一步,先准备一份简洁、优雅的简历模板!
后端·面试
慕木兮人可10 小时前
Docker部署MySQL镜像
spring boot·后端·mysql·docker·ecs服务器
发粪的屎壳郎10 小时前
ASP.NET Core 8 轻松配置Serilog日志
后端·asp.net·serilog
倔强青铜三11 小时前
苦练Python第4天:Python变量与数据类型入门
前端·后端·python