Google Protocol Buffers和java字符串处理控制
大多數(shù)的操作碼被從夜晚復(fù)制。懶得敲。
直接在源代碼和測試結(jié)果如下。
serabuffer.proto檔。使用下面的命令來生成java代碼。
protoc -I=./ --java_out=./ serabuffer.proto
以下是java部分代碼。直接輸出結(jié)果,要測試不同字符串長度的,能夠直接替換當(dāng)中的字符串然后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("及基于消息的協(xié)調(diào)機(jī)制不適合在某些應(yīng)用中使用,因此須要有一種可靠的、可擴(kuò)展的、分布式的、可配置的協(xié)調(diào)機(jī)制來統(tǒng)一系統(tǒng)的狀態(tài)"); 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+" 耗時(shí):"+(s2-s1)); long a1=System.nanoTime(); t.deserialize(ByteString.copyFrom(b));long a2=System.nanoTime(); System.out.println("反序列化耗時(shí):"+(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("及基于消息的協(xié)調(diào)機(jī)制不適合在某些應(yīng)用中使用,因此須要有一種可靠的、可擴(kuò)展的、分布式的、可配置的協(xié)調(diào)機(jī)制來統(tǒng)一系統(tǒng)的狀態(tài)").append("?").append("10").append("?").append("http://xxx.jpg");byte[] c=sb.toString().getBytes();long s4=System.nanoTime();System.out.println("拼接字符后長度:"+c.length+" 耗時(shí):"+(s4-s3));long c1=System.nanoTime(); sb.toString().split("?");long c2=System.nanoTime(); System.out.println("拆字符串耗時(shí):"+(c2-c1)); } }
1、字符串長度較短時(shí):
序列化后長度是:50 耗時(shí):32115919
拼接字符后長度:56 耗時(shí):36223
反序列化耗時(shí):2484294
拆字符串耗時(shí):305783
2、字符串長度較長時(shí),也就是如今代碼中的。
序列化后長度是:265 耗時(shí):20092297
拼接字符后長度:229 耗時(shí):48297
反序列化耗時(shí):2445656
拆字符串耗時(shí):354683
3、字符串長度再加長時(shí)
序列化后長度是:435 耗時(shí):26542406
拼接字符后長度:398 耗時(shí):53127
反序列化耗時(shí):5412019
拆字符串耗時(shí):527950
結(jié)果:
1、速度方面,拼接字符串速度是序列化的500-1000倍。拆分字符串是反序列化的8倍左右。
2、大小方面。數(shù)據(jù)小的序列化的體積小,數(shù)據(jù)大了以后,字符串拼接有優(yōu)勢;
3、上面結(jié)果數(shù)據(jù)事實(shí)上是不固定的,和詳細(xì)的數(shù)據(jù)有關(guān)。
結(jié)論:
網(wǎng)上的資料顯示。protocol buffer在序列化方面無論提交還是性能方面都是非常優(yōu)秀的,可是這里的測試結(jié)果顯示和字符串處理方式來比差距就太明顯了。
不要迷信,須要自己測試過才有體會(huì),有些場景。用字符串處理的方式比序列化的方式更有優(yōu)勢。消息中間件假設(shè)用字符串的方式來處理。性能應(yīng)該成倍增加。
版權(quán)聲明:本文博主原創(chuàng)文章,博客,未經(jīng)同意不得轉(zhuǎn)載。
轉(zhuǎn)載于:https://www.cnblogs.com/mfrbuaa/p/4914597.html
總結(jié)
以上是生活随笔為你收集整理的Google Protocol Buffers和java字符串处理控制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法与数据结构题目的 PHP 实现:栈和
- 下一篇: TF卡 SD卡接口