[]字节(字符串)的代价是多少? [英] How expensive is []byte(string)?

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

问题描述

我们将字符串转换为 [] byte

Let's convert string to []byte:

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

这个投射操作有多昂贵?复制是否执行?就我看到的Go规范而言:字符串的行为像字节片段但是不可变,这应该至少包括复制以确保后续的片操作不会修改我们的字符串 s 。反向对话会发生什么?是否 []字节< - > 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?

推荐答案

c $ c> [] byte(s)不是转换,而是转换。某些转换与转换相同,如 uint(myIntvar),它只是重新解释中的位。不幸的是,这不是字符到字节片转换的情况。字节切片是可变的,字符串(精确的字符串值)不是。结果是正在创建的字符串的必要副本(mem alloc + content transfer)。所以是的,在某些情况下它可能是昂贵的。

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.

这篇关于[]字节(字符串)的代价是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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