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

cmd/compile: redundant allocation & copy in return string([]byte) #51937

Closed
jfcg opened this issue Mar 25, 2022 · 1 comment
Closed

cmd/compile: redundant allocation & copy in return string([]byte) #51937

jfcg opened this issue Mar 25, 2022 · 1 comment

Comments

@jfcg
Copy link

@jfcg jfcg commented Mar 25, 2022

What version of Go are you using (go version)?

go1.17.8

Does this issue reproduce with the latest release?

yes also with go1.18

What operating system and processor architecture are you using (go env)?

x86_64 Linux

What did you do?

pkg.go

package pkg

// ToLower converts ascii string s to lower-case
func ToLower(s string) string {
	if s == "" {
		return ""
	}
	buf := make([]byte, len(s))

	for i := 0; i < len(s); i++ {
		c := s[i]
		if 'A' <= c && c <= 'Z' {
			c |= 32
		}
		buf[i] = c
	}
	return string(buf)
}

pkg_test.go

package pkg

import "testing"

func BenchmarkToLower(b *testing.B) {
	str := "SomE StrInG"
	want := "some string"
	var res string

	for i := 0; i < b.N; i++ {
		res = ToLower(str)
	}
	if res != want {
		b.Fatal("ToLower error")
	}
}

go test -v -bench ToLower -benchmem -count=3 prints

BenchmarkToLower-4      18710726                66.86 ns/op           32 B/op          2 allocs/op
BenchmarkToLower-4      17420910                65.57 ns/op           32 B/op          2 allocs/op
BenchmarkToLower-4      17085405                63.16 ns/op           32 B/op          2 allocs/op

What did you expect to see?

I was expecting to see a single memory allocation in ToLower() since there is no other reference to buf.

What did you see instead?

As is clear in bench output, there must a redundant allocation & copy in return string(buf).

@seankhliao seankhliao changed the title cmd/go: redundant buffer allocation & copy runtime: redundant allocation & copy in return string([]byte) Mar 25, 2022
@seankhliao
Copy link
Contributor

@seankhliao seankhliao commented Mar 25, 2022

I think this is a dup of #50846
Please comment if you disagree

@seankhliao seankhliao changed the title runtime: redundant allocation & copy in return string([]byte) cmd/compile: redundant allocation & copy in return string([]byte) Mar 25, 2022
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

2 participants