Creating a byte fragment with a known text string in the Golang

I have this text that I would like to add to a byte fragment:

s := "There are these two young fish swimming along and they happen to meet an older fish swimming the other way" 

If i write

 b := []byte("There are these two young fish swimming along and they happen to meet an older fish swimming the other way") 

As I understand it, at runtime it will be:

  • create a string with values ​​in memory
  • create byte fragment
  • copy the contents of the string to a byte slice (redistributing if necessary)

I could convert each of the string values ​​to their ASCII equivalent and directly create a byte slice:

 b := []byte{84, 104, ... } 

although it is not very readable.

I understand that the example here is a little trivial, and most computers can do this instantly, but I'm interested. Does the compiler interpret []byte("blah") and turn it into an efficient byte fragment at compile time? Would a better solution change if the string contains non-ASCII characters?

+6
source share
2 answers

Go inserts a string into an executable program as a string literal. It converts a string literal to a byte slice at runtime using the runtime.stringtoslicebyte function.

+3
source

If you initialize the variable []byte from a constant string, it seems that the compiler is smart enough not to create an intermediate string: instead, the substitution array for the byte segment is initialized directly from the static data, and not to construct the string variable first.

There is a copy of the data, but this should be expected when creating a mutable type.

+2
source

Source: https://habr.com/ru/post/974897/


All Articles