1. 程式人生 > >go 實現高效的 byte 連線

go 實現高效的 byte 連線

在go語言中,bytes.Buffer提供了高效的多個bytes連線。

舉個栗子:

1)多個[]byte 連線

  b1:=[]byte("this is a first string")

  b2:=[]byte("this is a second string")

  var buffer bytes.Buffer //Buffer是一個實現了讀寫方法的可變大小的位元組緩衝

  buffer.Write(b1)

  buffer.Write(b2)

  b3 :=buffer.Bytes()  //得到了b1+b2的結果

2)多個string相連

  str1:="this is a first string"

  str2:="this is a second string"

  buffer.WriteString(str1)

  buffer.WriteString(str2)

  str3 :=buffer.String()  //得到了str1+str2的結果

  同學們可能疑惑了,兩個string相加不是用str1+str2麼?  

   可以的,但是用bytes.Buffer方式更加的高效,類似於java中的stringBuffer類,

   實現了字串或者字元陣列的高效連線,比+拼接方式高效了至少1個數量級。