初级会员
  • 第 59368 位会员
  • douyacun
  • douyacun
  • douyacun@github.com
  • 2021-01-14 07:20:53
  • Offline
  • 20 14

最近分享的资源

    暂无

最近发布的项目

    暂无

最近的评论

  • #3 @focusonline 我实际测试了一下,拼接 1-10万数字 ```go func main() { a := make([]string, 100000) for i := 1; i <= 100000; i++ { a = append(a, strconv.Itoa(i)) } fmt.Println(unsafe.Sizeof(a)) // -- 预热 fmt.Println("--- 预热") Builder(a) buffer(a) fmt.Println("--- 开始") Builder(a) buffer(a) } func buffer(a []string) { start := time.Now() var str = bytes.NewBufferString("") for _, i := range a { str.WriteString(i) } latency := time.Now().Sub(start) fmt.Printf("buffer latency: %s len: %d\n", latency, len(str.String())) } func Builder(a []string) { start := time.Now() var str = strings.Builder{} for _, i := range a { str.WriteString(i) } latency := time.Now().Sub(start) fmt.Printf("builder latency: %s len: %d\n", latency, len(str.String())) } ``` 第一次: --- 预热 builder latency: 3.25557ms len: 488895 buffer latency: 4.47419ms len: 488895 --- 开始 builder latency: 6.116895ms len: 488895 buffer latency: 6.607627ms len: 488895 第二次: --- 预热 builder latency: 3.336517ms len: 488895 buffer latency: 2.084284ms len: 488895 --- 开始 builder latency: 2.634188ms len: 488895 buffer latency: 2.930336ms len: 488895 多次测试,都是Builder快一点,@ focusonline 牛逼
  • 1楼 @focusonline ```go type Builder struct { addr *Builder // of receiver, to detect copies by value buf []byte } ``` ```go type Buffer struct { buf []byte // contents are the bytes buf[off : len(buf)] off int // read at &buf[off], write at &buf[len(buf)] lastRead readOp // last read operation, so that Unread* can work correctly. } ``` 都是存储字节slice的, - Builder writeString是append到buf中,会有扩容操作, - Buffer writeString 是通过copy内存实现的 Buffer用起来更顺手