Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StringToBytes is slower than the raw convertion #3935

Open
Aden-Q opened this issue Apr 26, 2024 · 0 comments
Open

StringToBytes is slower than the raw convertion #3935

Aden-Q opened this issue Apr 26, 2024 · 0 comments

Comments

@Aden-Q
Copy link

Aden-Q commented Apr 26, 2024

Description

I ran the given benchmark in bytesconv_test.go to compare the performance of converting a string to bytes using:

  1. unsafe conversion:
    func StringToBytes(s string) []byte {
    return unsafe.Slice(unsafe.StringData(s), len(s))
    }
  2. raw conversion:
    func rawStrToBytes(s string) []byte {
    return []byte(s)
    }

And found that both methods have 0 memory allocation and the raw conversion is a little faster than the unsafe one:

╰─± go test -v -run=none -bench=^BenchmarkBytesConvStr -benchmem=true
goos: darwin
goarch: amd64
pkg: github.com/gin-gonic/gin/internal/bytesconv
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkBytesConvStrToBytesRaw
BenchmarkBytesConvStrToBytesRaw-12      1000000000               0.2571 ns/op          0 B/op          0 allocs/op
BenchmarkBytesConvStrToBytes
BenchmarkBytesConvStrToBytes-12         1000000000               0.5216 ns/op          0 B/op          0 allocs/op
PASS
ok      github.com/gin-gonic/gin/internal/bytesconv     1.104s

The repo uses the unsafe conversion in a few places at this moment, which may not be necessary at all. 2 reasons why we don't want to use the unsafe version:

  1. The raw conversion is slightly faster than the unsafe version
  2. unsafe is unsafe, as the name suggests

The PR to fix: #3936

How to reproduce

  1. clone the repo
  2. cd internal/bytesconv
  3. go test -v -run=none -bench=^BenchmarkBytesConvStr -benchmem=true

Expectations

Actual result

raw conversion is slightly faster than unsafe conversion. Both have zero memory allocation.

Environment

  • go version: go version go1.22.2 darwin/amd64
  • gin version (or commit ref): [0397e5e](https://github.com/gin-gonic/gin/commit/0397e5e0c0f8f8176c29f7edd8f1bff8e45df780)
  • operating system: darwin/amd64 (macOS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant