Go Benchmark
String to Bytes Conversion
The cost of []byte(s) and string(b) — and the unsafe zero-copy alternative.
Converting between string and []byte is everywhere in Go: hashing, writing to sockets, JSON encoding. Because strings are immutable, the standard conversions []byte(s) and string(b) allocate and copy the entire payload every time. Since Go 1.20, unsafe.String and unsafe.Slice (with unsafe.StringData / unsafe.SliceData) allow reinterpreting the same memory with zero copies — the same trick the standard library uses internally in strings.Builder. This benchmark shows what the safe conversions cost for a 128-byte payload and what the unsafe route saves. The "Bytes" tab converts string → []byte, the "String" tab converts []byte → string.
1 CPU
32 CPUs
Uses unsafe.Slice(unsafe.StringData(s), len(s)) and unsafe.String(unsafe.SliceData(b), len(b)) to reinterpret the existing memory: no allocation, no copy, constant time regardless of size. The contract is on you: mutating the resulting bytes (or the source slice) is undefined behavior. Only reach for this on measured hot paths where the data is provably never modified.
The built-in conversions []byte(s) and string(b). Each one allocates fresh memory and copies the whole payload, because the compiler must guarantee that the immutable string and the mutable slice never share memory. Safe, idiomatic, and the right default — the cost scales with payload size.
Contributors