Online I have seen two methods converting a byte array to a string in Go.
Method 1:
func convert(myBytes byte[]) string {
myString := string(myBytes[:])
return myString
}
Method 2:
func convert(b []byte) string {
return *((*string)(unsafe.Pointer(&b)))
}
What is the difference? Which one is faster? Which one should I use?
CodePudding user response:
The first form copies the byte slice to a new array, and creates a string pointing to that. The second one creates a string pointing to the given byte slice.
The first one is safe, but has a copy operation. The second one is unsafe, and the program will break with hard to diagnose errors if you ever modify the contents of the given byte slice, because strings are supposed to be immutable. But it does not have a copy operation.
It is very unlikely that this is a bottleneck. Array copy is a fast operation. Use the first version.