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
相关推荐
这里有鱼汤4 分钟前
通过AI狂赚苹果26.6%,这套AI金融交易开源Agent彻底火了
后端·agent
寻月隐君13 分钟前
【Solana 开发实战】轻松搞定链上 IDL:从上传到获取全解析
后端·web3·github
程序员爱钓鱼23 分钟前
Go项目上线部署最佳实践:Docker容器化从入门到进阶
后端·google·go
汪子熙25 分钟前
Visual Studio Code 中排除指定文件夹搜索的最佳实践与实现原理
后端·面试
大P哥阿豪1 小时前
Go defer(二):从汇编的角度理解延迟调用的实现
开发语言·汇编·后端·golang
风象南1 小时前
SpringBoot 与 HTMX:现代 Web 开发的高效组合
java·spring boot·后端
wstcl2 小时前
让你的asp.net网站在调试模式下也能在局域网通过ip访问
后端·tcp/ip·asp.net
ai小鬼头10 小时前
Ollama+OpenWeb最新版0.42+0.3.35一键安装教程,轻松搞定AI模型部署
后端·架构·github
萧曵 丶10 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
老任与码11 小时前
Spring AI Alibaba(1)——基本使用
java·人工智能·后端·springaialibaba