[UMU 学 golang](8) strings.Builder vs bytes.Buffer

原创
2018/04/02 18:47
阅读数 1K

先说优点

  • strings.Builder:省内存
  • bytes.Buffer:快

性能测试程序

package benchmark_test

import (
	"bytes"
	"strings"
	"testing"
)

var (
	ss = "1234567890abcdefghijklmnopqrstuvwxyz"
	bs = []byte(ss)
	rn = 'a'
	bt = byte('a')
)

func BenchmarkBuilderWrite(b *testing.B) {
	var builder strings.Builder
	for i := 0; i < b.N; i++ {
		builder.Write(bs)
	}
}

func BenchmarkBuiderWriteByte(b *testing.B) {
	var builder strings.Builder
	for i := 0; i < b.N; i++ {
		builder.WriteByte(bt)
	}
}

func BenchmarkBuilderWriteRune(b *testing.B) {
	var builder strings.Builder
	for i := 0; i < b.N; i++ {
		builder.WriteRune(rn)
	}
}

func BenchmarkBuilderWriteString(b *testing.B) {
	var builder strings.Builder
	for i := 0; i < b.N; i++ {
		builder.WriteString(ss)
	}
}

func BenchmarkBufferWrite(b *testing.B) {
	var buffer bytes.Buffer
	for i := 0; i < b.N; i++ {
		buffer.Write(bs)
	}
}

func BenchmarkBufferWriteByte(b *testing.B) {
	var buffer bytes.Buffer
	for i := 0; i < b.N; i++ {
		buffer.WriteByte(bt)
	}
}

func BenchmarkBufferWriteRune(b *testing.B) {
	var buffer bytes.Buffer
	for i := 0; i < b.N; i++ {
		buffer.WriteRune(rn)
	}
}

func BenchmarkBufferWriteString(b *testing.B) {
	var buffer bytes.Buffer
	for i := 0; i < b.N; i++ {
		buffer.WriteString(ss)
	}
}
展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部