-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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
context: doc of WithValue should mention context is not data store #33283
Comments
I agree that the godoc should more clearly suggest what to do here. One thread that seems to cover this is https://stackoverflow.com/questions/40379960/golang-context-withvalue-how-to-add-several-key-value-pairs. |
/cc @Sajmani @bradfitz as per https://dev.golang.org/owners |
Just a drive by question: is there a particular reason why it’s recursive and not a loop? |
I don't think it could be written as a loop, since there's no way to get a context's parent context. |
Hi! Can I pick this up? |
@wuweiweiwu, that's fine for me. @ericlagergren, I think they preferred to have a simple and maintainable implementation over an efficient one. As we should mention in doc, Just for fun, I experimented with the code a bit and benchmarked few options. As far as I can see, there are thee alternative implementations, with different trade-offs in terms of performance. Here is a summary of my analysis.
|
Hello, as others have mentioned, we could certainly optimize the Context value lookup if and when that becomes a demonstrated performance bottleneck. I think that's preferable to documenting the current O(depth of context tree) lookup behavior, which is an implementation detail. |
I just wanted to reiterate and elaborate on my prior point: because |
Hello everybody,
go/src/context/context.go
Lines 520 to 525 in 9195948
Implementation of
valueCtx.Value
in context package is recursive function. That means its performance decreases at least linearly with the number of values stored in the context. Moreover, it is easily subject to stack overflow if user stores way too many values.Documentation does not give any advice on how
context.WithValue
should be used, especially w.r.t. performance. IMHO, it would be better to update the doc in order to:context.Context
as data store;valueCtx.Value
performance.CC @mvdan
The text was updated successfully, but these errors were encountered: