[]byte(string) 有多贵? [英] How expensive is []byte(string)?

查看:11
本文介绍了[]byte(string) 有多贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们把 string 转换成 []byte:

Let's convert string to []byte:

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

这种演员阵容有多贵?是否执行复制?据我在 Go 规范中看到:字符串的行为类似于字节切片,但不可变,这至少应该涉及复制以确保后续切片操作不会修改我们的字符串 s.反向对话会发生什么?[]byte <->string 对话涉及编码/解码,比如 utf8 <-> runes?

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?

推荐答案

[]byte(s) 不是演员表,而是 转换.一些转换与强制转换相同,例如 uint(myIntvar),它只是重新解释位就地.不幸的是,字符串到字节切片转换的情况并非如此.字节切片是可变的,字符串(准确地说是字符串值)不是.结果是正在制作的字符串的必要副本(内存分配+内容传输).所以是的,在某些情况下它可能会很昂贵.

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.

不执行编码转换.字符串(源)字节按原样复制到切片(目标)字节.

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

这篇关于[]byte(string) 有多贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆