gin icon indicating copy to clipboard operation
gin copied to clipboard

StringToBytes is slower than the raw convertion

Open Aden-Q opened this issue 3 weeks ago • 0 comments

Description

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

  1. unsafe conversion: https://github.com/gin-gonic/gin/blob/0397e5e0c0f8f8176c29f7edd8f1bff8e45df780/internal/bytesconv/bytesconv_1.20.go#L15-L17
  2. raw conversion: https://github.com/gin-gonic/gin/blob/0397e5e0c0f8f8176c29f7edd8f1bff8e45df780/internal/bytesconv/bytesconv_test.go#L22-L24

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: https://github.com/gin-gonic/gin/pull/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)

Aden-Q avatar Apr 26 '24 16:04 Aden-Q