Protostuf序列化
工具对比
JdkSerialize
: java内置的序列化能将实现了Serilazable接口的对象进行序列化和反序列化,ObjectOutputStream的writeObject0方法可序列化对象生成字节数组
Protostuf
:google开源的protostuf采用更为紧凑的二进制数组,表现更加优异,然后使用protostuff的编译工具生成pojo类
代码实现
导入依赖
io.protostuff protostuff-core 1.6.0 io.protostuff protostuff-runtime 1.6.0
创建工具类
import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; public class ProtostuffUtil { /** * 序列化 * @param t * @param * @return */ public static 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 * @return */ public static T deserialize(byte []bytes,Class 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; } }
测试
/** * jdk序列化与protostuff序列化对比 * @param args */ public static void main(String[] args) { long start =System.currentTimeMillis(); for (int i = 0; i