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

use unsafe.String #371

Closed
karelbilek opened this issue Oct 10, 2024 · 7 comments
Closed

use unsafe.String #371

karelbilek opened this issue Oct 10, 2024 · 7 comments

Comments

@karelbilek
Copy link

since go1.20, there is unsafe.String/unsafe.StringData

Looks like this

// to convert string to byte slice
unsafe.Slice(unsafe.StringData(s), len(s))

// to convert byte slice to string
return unsafe.String(&b[0], len(b))

I have found these functions really fast. (and it's also much faster to directly inline their usage rather than put them in a wrapper function, btw.)

I think those might be useful here. I will try to have a look where would I add them :D

@karelbilek
Copy link
Author

See

golang/go#53003

@karelbilek
Copy link
Author

I see that you actually use

func UnsafeString(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

which should be roughly the same. So.... I guess it's the same

@klauspost
Copy link
Collaborator

You are welcome to send a PR as a cosmetic fix. We are at minimum Go 1.20, so it should be fine.

@karelbilek
Copy link
Author

I will first try to bench first if it makes anything faster.

@klauspost
Copy link
Collaborator

99% sure it will be the same. I am willing to be surprised, though :)

@karelbilek
Copy link
Author

yeah it seems exactly the same with regards to speed, even when I inline; not sure why my earlier experiments were so different, probably noise. OK I will make a PR but it will be really just a cosmetic change

@philhofer
Copy link
Member

FWIW the UnsafeString function was used by the code generator to turn slices into strings temporarily so that we could switch on them when decoding structs. This was back before the compiler understood that it could avoid any allocations when you wrote switch string(buf) { case "xyz": ... }. Nowadays it's no longer necessary.

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

Successfully merging a pull request may close this issue.

3 participants