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

net/http: Request.WithContext is slow #28737

Open
go101 opened this Issue Nov 12, 2018 · 2 comments

Comments

Projects
None yet
3 participants
@go101

go101 commented Nov 12, 2018

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.

@go101

This comment has been minimized.

go101 commented Nov 12, 2018

I counted the number of native word copied in WithContext function. The number is 43+.

@bradfitz bradfitz changed the title from net/http: http.Request.WithContext is very slow. Need an alternative way to set context key-value to net/http: Request.WithContext is slow Nov 12, 2018

@bradfitz bradfitz added this to the Unplanned milestone Nov 12, 2018

@OneOfOne

This comment has been minimized.

Contributor

OneOfOne commented Nov 13, 2018

.WithContext returns a full copy of the request + URL, so it's expected to be heavy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment