日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

GoLang中拼接字符串性能優化方法詳解_Golang

作者:raoxiaoya ? 更新時間: 2023-04-03 編程語言

字符串在內存中是不可變的,放在只讀內存段,因此你可以使用str[0]來訪問,但是不能使用str[0]='a'來修改。

修改字符串實際上是重新放入新的地址,因此拼接字符串可能出現的性能問題就是頻繁的內存分配,比如:

func s1(ids []string) (s string) {
	for _, id := range ids {
		s += id
	}
	return
}

在golang中,具有預先分配內存特性的是切片,如果預先就分配好內存,然后再依次將字符串裝進去就避免了內存的頻繁分配。

再來看看strings包的實現

func Join(elems []string, sep string) string {
	switch len(elems) {
	case 0:
		return ""
	case 1:
		return elems[0]
	}
	n := len(sep) * (len(elems) - 1)
	for i := 0; i < len(elems); i++ {
		n += len(elems[i])
	}
	var b Builder
	b.Grow(n)
	b.WriteString(elems[0])
	for _, s := range elems[1:] {
		b.WriteString(sep)
		b.WriteString(s)
	}
	return b.String()
}

主要就用到strings.Builder對象,它包含一個切片。

type Builder struct {
	addr *Builder // of receiver, to detect copies by value
	buf  []byte
}

BuilderGrow方法就是主動擴容切片的容積。

// grow copies the buffer to a new, larger buffer so that there are at least n
// bytes of capacity beyond len(b.buf).
func (b *Builder) grow(n int) {
	buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)
	copy(buf, b.buf)
	b.buf = buf
}
// Grow grows b's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to b
// without another allocation. If n is negative, Grow panics.
func (b *Builder) Grow(n int) {
	b.copyCheck()
	if n < 0 {
		panic("strings.Builder.Grow: negative count")
	}
	if cap(b.buf)-len(b.buf) < n {
		b.grow(n)
	}
}

原文鏈接:https://blog.csdn.net/raoxiaoya/article/details/124629601

欄目分類
最近更新