2.编写工具类com.dyuproject.protostuff protostuff-core1.0.8 com.dyuproject.protostuff protostuff-runtime1.0.8
package com.test.protobuf; import com.alibaba.fastjson.JSON; import io.protostuff.linkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ProtostuffSerializeUtil { private static linkedBuffer buffer = linkedBuffer.allocate(linkedBuffer.DEFAULT_BUFFER_SIZE); private static Map3.编写测试类, Schema>> schemaCache = new ConcurrentHashMap , Schema>>(); public static byte[] serialize(T obj) { if (obj == null) { throw new NullPointerException(); } Class clazz = (Class ) obj.getClass(); Schema schema = getSchema(clazz); byte[] data; try { data = ProtostuffIOUtil.toByteArray(obj, schema, buffer); } finally { buffer.clear(); } return data; } public static T deserialize(byte[] data, Class clazz) { Schema schema = getSchema(clazz); T obj = schema.newMessage(); ProtostuffIOUtil.mergeFrom(data, obj, schema); return obj; } private static Schema getSchema(Class clazz) { Schema schema = (Schema ) schemaCache.get(clazz); if (schema == null) { // 这个schema通过RuntimeSchema进行懒创建并缓存 // 所以可以一直调用RuntimeSchema.getSchema(),这个方法是线程安全的 schema = RuntimeSchema.getSchema(clazz); if (schema != null) { schemaCache.put(clazz, schema); } } return schema; } }
package com.test.protobuf; import com.alibaba.fastjson.JSON; import com.evs.fes.entity.SysLog; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; public class MainTest { public static void main(String[] args) { int count = 100; List4.结论bytes = Lists.newArrayList(); for (int i = 0; i < count; i++) { Map map = Maps.newHashMap(); map.put("name", "zhangsan_" + i); map.put("score", i % 5); byte[] serialize = ProtostuffSerializeUtil.serialize(map); StringBuilder builder = new StringBuilder(); for (byte aSerialize : serialize) { builder.append(aSerialize); } System.out.println("==================第" + i + "行===================="); System.out.println(builder); bytes.add(serialize); } List
1.Protobuf序列化的压缩率优秀,但经笔者测试,其序列化效率并不高,对比fastjson没有明显的性能优势;
2.Protobuf反序列化性能明显优于fastjson,但缺点也一样突出,就是序列化后的内容可读性差。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)