gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.75k stars 8.01k forks source link

StringToBytes is slower than the raw convertion #3935

Open Aden-Q opened 6 months ago

Aden-Q commented 6 months ago

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

JimChenWYU commented 2 months ago

image image