go / expert
Snippet
Zero-Copy Byte Slice to String Conversion via unsafe.SliceData and unsafe.String
Standard string conversions perform heap re-allocations to copy backing byte arrays. By leveraging Go 1.20+ primitives unsafe.SliceData, unsafe.String, and unsafe.StringData, zero-copy conversions can be safely constructed without reflecting onto raw memory headers.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package mainimport ("fmt""unsafe")func FastBytesToString(b []byte) string {if len(b) == 0 {return ""}return unsafe.String(unsafe.SliceData(b), len(b))}func FastStringToBytes(s string) []byte {if len(s) == 0 {return nil}return unsafe.Slice(unsafe.StringData(s), len(s))}func main() {buf := []byte("Zero Allocation High Performance String")str := FastBytesToString(buf)back := FastStringToBytes(str)fmt.Printf("String: %s, Bytes len: %d\n", str, len(back))}
Breakdown
1
unsafe.String(unsafe.SliceData(b), len(b))
Obtains the underlying pointer of a byte slice and casts it directly into an immutable string reference.
2
unsafe.Slice(unsafe.StringData(s), len(s))
Converts a string pointer into a byte slice view sharing the exact memory block.