Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第十章关于strings.Join和strings.Builder效率比较的问题 #39

Open
miranquil opened this issue Oct 12, 2020 · 0 comments
Open

Comments

@miranquil
Copy link

miranquil commented Oct 12, 2020

参考源码,Join本身就是调用了套了一个Builder来存新字符串,所以这两个效率应该是一样的?
go1.15.2 darwin/amd6

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是个改写版的迷你bytes.Buffer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant