Google Protocol Buffers和java字符串处理控制
大多數的操作碼被從夜晚復制。懶得敲。
直接在源代碼和測試結果如下。
serabuffer.proto檔。使用下面的命令來生成java代碼。
protoc -I=./ --java_out=./ serabuffer.proto
以下是java部分代碼。直接輸出結果,要測試不同字符串長度的,能夠直接替換當中的字符串然后run就可以。 package Feinno.Practice.Learn;import com.google.protobuf.ByteString;public class Test {public byte[] serialize(){ProtoBufferPractice.msgInfo.Builder builder=ProtoBufferPractice.msgInfo.newBuilder(); builder.setGoodID(100); builder.setGuid("11111-23222-3333-444"); builder.setOrder(0); builder.setType("及基于消息的協調機制不適合在某些應用中使用,因此須要有一種可靠的、可擴展的、分布式的、可配置的協調機制來統一系統的狀態"); builder.setID(10); builder.setUrl("http://www.gufensoso.com/search/?q=java+protocol+buffer"); ProtoBufferPractice.msgInfo info=builder.build(); byte[] result=info.toByteArray() ; return result;}public void deserialize(ByteString result){try{ ProtoBufferPractice.msgInfo msg = ProtoBufferPractice.msgInfo.parseFrom(result); // System.out.println(msg); } catch(Exception ex){ System.out.println(ex.getMessage()); }}public static void main(String[] args) {Test t=new Test();long s1=System.nanoTime();byte[] b = t.serialize();long s2=System.nanoTime(); System.out.println("序列化后長度是:"+b.length+" 耗時:"+(s2-s1)); long a1=System.nanoTime(); t.deserialize(ByteString.copyFrom(b));long a2=System.nanoTime(); System.out.println("反序列化耗時:"+(a2-a1)); long s3=System.nanoTime(); StringBuilder sb=new StringBuilder();sb.append("?").append("100").append("?").append("11111-23222-3333-444").append("?").append("0").append("?").append("及基于消息的協調機制不適合在某些應用中使用,因此須要有一種可靠的、可擴展的、分布式的、可配置的協調機制來統一系統的狀態").append("?").append("10").append("?").append("http://xxx.jpg");byte[] c=sb.toString().getBytes();long s4=System.nanoTime();System.out.println("拼接字符后長度:"+c.length+" 耗時:"+(s4-s3));long c1=System.nanoTime(); sb.toString().split("?");long c2=System.nanoTime(); System.out.println("拆字符串耗時:"+(c2-c1)); } }
1、字符串長度較短時:
序列化后長度是:50 耗時:32115919
拼接字符后長度:56 耗時:36223
反序列化耗時:2484294
拆字符串耗時:305783
2、字符串長度較長時,也就是如今代碼中的。
序列化后長度是:265 耗時:20092297
拼接字符后長度:229 耗時:48297
反序列化耗時:2445656
拆字符串耗時:354683
3、字符串長度再加長時
序列化后長度是:435 耗時:26542406
拼接字符后長度:398 耗時:53127
反序列化耗時:5412019
拆字符串耗時:527950
結果:
1、速度方面,拼接字符串速度是序列化的500-1000倍。拆分字符串是反序列化的8倍左右。
2、大小方面。數據小的序列化的體積小,數據大了以后,字符串拼接有優勢;
3、上面結果數據事實上是不固定的,和詳細的數據有關。
結論:
網上的資料顯示。protocol buffer在序列化方面無論提交還是性能方面都是非常優秀的,可是這里的測試結果顯示和字符串處理方式來比差距就太明顯了。
不要迷信,須要自己測試過才有體會,有些場景。用字符串處理的方式比序列化的方式更有優勢。消息中間件假設用字符串的方式來處理。性能應該成倍增加。
版權聲明:本文博主原創文章,博客,未經同意不得轉載。
轉載于:https://www.cnblogs.com/mfrbuaa/p/4914597.html
總結
以上是生活随笔為你收集整理的Google Protocol Buffers和java字符串处理控制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法与数据结构题目的 PHP 实现:栈和
- 下一篇: TF卡 SD卡接口