Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is []byte(string)?

Tags:

Let's convert string to []byte:

func toBytes(s string) []byte {   return []byte(s) // What happens here? } 

How expensive is this cast operation? Is copying performed? As far as I see in Go specification: Strings behave like slices of bytes but are immutable, this should involve at least copying to be sure subsequent slice operations will not modify our string s. What happens with reverse conversation? Does []byte <-> string conversation involve encoding/decoding, like utf8 <-> runes?

like image 772
demi Avatar asked Jan 17 '13 06:01

demi


1 Answers

The []byte(s) is not a cast but a conversion. Some conversions are the same as a cast, like uint(myIntvar), which just reinterprets the bits in place. Unfortunately that's not the case of string to byte slice conversion. Byte slices are mutable, strings (string values to be precise) are not. The outcome is a necessary copy (mem alloc + content transfer) of the string being made. So yes, it can be costly in some scenarios.

EDIT: No encoding transformation is performed. The string (source) bytes are copied to the slice (destination) bytes as they are.

like image 175
zzzz Avatar answered Oct 03 '22 22:10

zzzz