When to use []byte or string in Go?

后端 未结 3 1952
眼角桃花
眼角桃花 2021-01-31 01:05

Frequently in writing Go applications, I find myself with the choice to use []byte or string. Apart from the obvious mutability of []byte,

3条回答
  •  -上瘾入骨i
    2021-01-31 02:08

    1. One difference is that the returned []byte can be potentially reused to hold another/new data (w/o new memory allocation), while string cannot. Another one is that, in the gc implementation at least, string is a one word smaller entity than []byte. Can be used to save some memory when there is a lot of such items live.

    2. Casting a []byte to string for logging is not necessary. Typical 'text' verbs, like %s, %q work for string and []byte expressions equally. In the other direction the same holds for e.g. %x or % 02x.

    3. Depends on why is the concatenation performed and if the result is ever to be again combined w/ something/somewhere else afterwards. If that's the case then []byte may perform better.

提交回复
热议问题