Home >Backend Development >Golang >How to Efficiently Convert UTF-8 Strings to Byte Arrays in Go?

How to Efficiently Convert UTF-8 Strings to Byte Arrays in Go?

DDD
DDDOriginal
2024-10-29 07:47:30675browse

How to Efficiently Convert UTF-8 Strings to Byte Arrays in Go?

Converting UTF-8 Strings to Byte Arrays

Unmarshalling JSON requires a byte slice input, while strings are stored as UTF-8 in Go. This article explores the efficient conversion of UTF-8 strings to byte arrays.

Direct Conversion

Go allows converting strings to byte slices, creating a copy of the string's bytes:

<code class="go">s := "some text"
b := []byte(s)</code>

However, for large strings, this approach is inefficient due to the copying.

Using io.Reader

An efficient alternative is using strings.NewReader() to create an io.Reader that reads from the string without copying:

<code class="go">s := `{ "somekey": "somevalue" }`

var result interface{}
err := json.NewDecoder(strings.NewReader(s)).Decode(&result)</code>

This approach avoids copying the string.

Small JSON Texts

For small JSON texts, direct conversion remains a fast option:

<code class="go">s := `{ "somekey": "somevalue" }`

var result interface{}
err := json.Unmarshal([]byte(s), &result)</code>

Note: When reading JSON from an io.Reader (e.g., file or network), pass the io.Reader directly to json.NewDecoder() without intermediate string reads.

The above is the detailed content of How to Efficiently Convert UTF-8 Strings to Byte Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn