Improved performance

This commit is contained in:
Eduard Urbach 2024-03-14 00:06:20 +01:00
parent 9ec4621356
commit e604017ecc
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 10 additions and 16 deletions

View File

@ -40,17 +40,6 @@ type ctx struct {
handlerCount int handlerCount int
} }
// newContext returns a new context from the pool.
func newContext(req *http.Request, res http.ResponseWriter, server *Server) *ctx {
ctx := contextPool.Get().(*ctx)
ctx.request = req
ctx.response = res
ctx.server = server
ctx.paramCount = 0
ctx.handlerCount = 0
return ctx
}
// Bytes responds with a raw byte slice. // Bytes responds with a raw byte slice.
func (ctx *ctx) Bytes(body []byte) error { func (ctx *ctx) Bytes(body []byte) error {
_, err := ctx.response.Write(body) _, err := ctx.response.Write(body)

View File

@ -50,8 +50,8 @@ coverage: 100.0% of statements
## Benchmarks ## Benchmarks
``` ```
BenchmarkHello-12 31128832 38.41 ns/op 0 B/op 0 allocs/op BenchmarkHello-12 35983602 33.28 ns/op 0 B/op 0 allocs/op
BenchmarkGitHub-12 17406580 68.56 ns/op 0 B/op 0 allocs/op BenchmarkGitHub-12 18320769 68.66 ns/op 0 B/op 0 allocs/op
``` ```
## License ## License

View File

@ -61,15 +61,20 @@ func (server *Server) Put(path string, handler Handler) {
// ServeHTTP responds to the given request. // ServeHTTP responds to the given request.
func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) { func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
ctx := newContext(request, response, server) ctx := contextPool.Get().(*ctx)
defer contextPool.Put(ctx) ctx.request = request
ctx.response = response
ctx.server = server
err := server.handlers[0](ctx) err := server.handlers[0](ctx)
if err != nil { if err != nil {
response.(io.StringWriter).WriteString(err.Error()) response.(io.StringWriter).WriteString(err.Error())
log.Println(request.URL, err) log.Println(request.URL, err)
} }
ctx.paramCount = 0
ctx.handlerCount = 0
contextPool.Put(ctx)
} }
// Run starts the server on the given address. // Run starts the server on the given address.