[关闭]
@aliasliyu4 2016-07-16T07:44:18.000000Z 字数 976 阅读 2517

golang高效拼接字符串的方式

两种方式分别是buffer和array数组方式来拼接。

Buf()方法代表了buffer方式
join方法代表了arrary方式

  1. package csvtomysqlx
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. )
  7. var count1 int64
  8. func getNextString1() (string, bool) {
  9. if count1 < 1000000 {
  10. count1++
  11. return "test", true
  12. }
  13. return "end", false
  14. }
  15. func Buf() {
  16. var buffer bytes.Buffer
  17. for {
  18. if piece, ok := getNextString1(); ok {
  19. buffer.WriteString(piece)
  20. } else {
  21. break
  22. }
  23. }
  24. fmt.Println(len(buffer.String()) / 4)
  25. buffer.Reset()
  26. }
  27. var count2 int64
  28. func getNextString2() (string, bool) {
  29. if count2 < 1000000 {
  30. count2++
  31. return "test", true
  32. }
  33. return "end", false
  34. }
  35. func Join() {
  36. lagerslice := make([]string, 1000)
  37. for {
  38. if piece, ok := getNextString2(); ok {
  39. lagerslice = append(lagerslice, piece)
  40. } else {
  41. break
  42. }
  43. }
  44. join := strings.Join(lagerslice, "")
  45. fmt.Println(len(join) / 4)
  46. fmt.Println(len(lagerslice))
  47. }

测试代码:

  1. package test
  2. import (
  3. "csv/csvtomysqlx"
  4. "testing"
  5. )
  6. func TestBuf(t *testing.T) {
  7. csvtomysqlx.Buf()
  8. }
  9. func TestJoin(t *testing.T) {
  10. csvtomysqlx.Join()
  11. }

测试结果:

说明: 两种方式都是拼接100w个字符串,buffer的速度和array的速度是不在一个量级上的。而且数组的方式会带来更多的开销。所以对于超长的字符串拼接,建议使用buffer的方式。当然如果是少量的拼接。还是用fmt.Sprintf&+=的方式。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注