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

v3: Improve Performance of c.Body() by 125% #3090

Merged
merged 2 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,16 @@ func (c *DefaultCtx) Body() []byte {
encodingOrder = []string{"", "", ""}
)

// faster than peek
c.Request().Header.VisitAll(func(key, value []byte) {
if c.app.getString(key) == HeaderContentEncoding {
headerEncoding = c.app.getString(value)
// Get Content-Encoding header
headerEncoding = utils.UnsafeString(c.Request().Header.ContentEncoding())

// If no encoding is provided, return the original body
if len(headerEncoding) == 0 {
if c.app.config.Immutable {
return utils.CopyBytes(c.fasthttp.Request.Body())
}
})
return c.fasthttp.Request.Body()
}

// Split and get the encodings list, in order to attend the
// rule defined at: https://www.rfc-editor.org/rfc/rfc9110#section-8.4-5
Expand Down
27 changes: 27 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,16 @@ func Test_Ctx_Body(t *testing.T) {
require.Equal(t, []byte("john=doe"), c.Body())
}

// go test -run Test_Ctx_BodyRaw
func Test_Ctx_BodyRaw(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed

c.Request().SetBodyRaw([]byte("john=doe"))
require.Equal(t, []byte("john=doe"), c.BodyRaw())
}

// go test -v -run=^$ -bench=Benchmark_Ctx_Body -benchmem -count=4
func Benchmark_Ctx_Body(b *testing.B) {
const input = "john=doe"
Expand All @@ -373,6 +383,23 @@ func Benchmark_Ctx_Body(b *testing.B) {
require.Equal(b, []byte(input), c.Body())
}

// go test -v -run=^$ -bench=Benchmark_Ctx_BodyRaw -benchmem -count=4
func Benchmark_Ctx_BodyRaw(b *testing.B) {
const input = "john=doe"

app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed

c.Request().SetBodyRaw([]byte(input))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = c.BodyRaw()
}

require.Equal(b, []byte(input), c.BodyRaw())
}

// go test -run Test_Ctx_Body_Immutable
func Test_Ctx_Body_Immutable(t *testing.T) {
t.Parallel()
Expand Down
Loading