Skip to content

net/http: Request.WithContext is slow #28737

Closed
@zigo101

Description

@zigo101

What version of Go are you using (go version)?

go version go1.11.2 linux/amd64

Does this issue reproduce with the latest release?

yes

What did you do?

I write a http router package: https://github.com/go101/tinyrouter
The benchmark result shows it spends about 3x times (24136 ns / 7285 ns/op) to match a pattern as HttpRouter.
After some profiling, I found the slowness is mainly caused by one line in my package:

req = req.WithContext(context.WithValue(req.Context(), paramsKeyType{}, Params{path, tokens}))

This line spends about 11000 ns. In the 11000 ns, 8000ns is spent on the req.WithContext() call.

If my package doesn't return URL path params through context (as HttpRouter does), then it only 30% slower than HttpRouter.

Considering that sometimes there may be more values to be appended into the context, it will spend more time. So I think we really need an alternative faster way to append key-values to http request context.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions