From 0cf6349204fb4463eb103e6ff8bb4341d5f12adf Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Sat, 29 Jun 2024 01:55:54 +0300 Subject: [PATCH] prefer rwmutex, add parallel benchmark --- router.go | 6 +++--- router_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/router.go b/router.go index cf36dede..0ab94132 100644 --- a/router.go +++ b/router.go @@ -146,7 +146,7 @@ func (app *App) nextCustom(c CustomCtx) (bool, error) { //nolint: unparam // boo } func (app *App) next(c *DefaultCtx) (bool, error) { - app.mutex.Lock() + app.mutex.RLock() // Get stack length tree, ok := app.treeStack[c.methodINT][c.treePath] @@ -154,7 +154,7 @@ func (app *App) next(c *DefaultCtx) (bool, error) { tree = app.treeStack[c.methodINT][""] } lenTree := len(tree) - 1 - app.mutex.Unlock() + app.mutex.RUnlock() // Loop over the route stack starting from previous index for c.indexRoute < lenTree { @@ -381,7 +381,7 @@ func (app *App) addRoute(method string, route *Route, isMounted ...bool) { app.mutex.Lock() defer app.mutex.Unlock() - fmt.Printf("addRoute: method: %s, route: %v, isMounted: %v\n", method, route, isMounted) + //fmt.Printf("addRoute: method: %s, route: %v, isMounted: %v\n", method, route, isMounted) // Check mounted routes var mounted bool diff --git a/router_test.go b/router_test.go index 300614b2..2e1620f8 100644 --- a/router_test.go +++ b/router_test.go @@ -595,6 +595,34 @@ func Benchmark_Router_Next(b *testing.B) { require.Equal(b, 4, c.indexRoute) } +func Benchmark_Router_Next_Parallel(b *testing.B) { + app := New() + registerDummyRoutes(app) + app.startupProcess() + + request := &fasthttp.RequestCtx{} + + request.Request.Header.SetMethod("DELETE") + request.URI().SetPath("/user/keys/1337") + var res bool + var err error + + c := app.AcquireCtx(request).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + + b.ResetTimer() + + b.RunParallel(func(p *testing.PB) { + for p.Next() { + c.indexRoute = -1 + res, err = app.next(c) + } + }) + + require.NoError(b, err) + require.True(b, res) + require.Equal(b, 4, c.indexRoute) +} + // go test -v ./... -run=^$ -bench=Benchmark_Route_Match -benchmem -count=4 func Benchmark_Route_Match(b *testing.B) { var match bool