Skip to content
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: allow pre-allocation of valueCtx #42329

Closed
RaduBerinde opened this issue Nov 2, 2020 · 2 comments
Closed

context: allow pre-allocation of valueCtx #42329

RaduBerinde opened this issue Nov 2, 2020 · 2 comments

Comments

@RaduBerinde
Copy link
Contributor

In various CockroachDB workloads, context.WithValue shows up as a few percentage points in profiles (similar to any other object allocation). In many cases, we also allocate an object for the value that is associated with the context. We would like to consolidate these allocations by embedding valueCtx inside a bigger struct, so that we can allocate both objects together.

Note that we can't have our own implementation of Context without losing some efficiency because parentCancelCtx won't be aware of it.

My proposal is to export the valueCtx type (or an alias) and provide a method or WithValue variant to initialize it. Would this kind of addition to the API be acceptable? (I can post the change if yes)

@zikaeroh
Copy link
Contributor

zikaeroh commented Nov 2, 2020

It was my impression that CL 196521 modified parentCancelCtx such that it no longer uses known types to traverse upwards, but instead uses a value to look up the parent cancel context.

Meaning, you should be able to write this code:

type myValueContext struct {
    context.Context
    key   interface{}
    value *SomeValue
}

func (v myValueContext) Value(key interface{}) interface{} {
    if key == v.key {
        return v.value
    }
    return v.Context.Value(key)
)

And it only incur a single allocation (ignoring my placeholder types). On a WithCancel, the value stack is searched for the parent, and that works as before.

@RaduBerinde
Copy link
Contributor Author

Ah, awesome! Yeah that does it. I had checked the source at https://golang.org/src/context/context.go?s=8419:8483#L222 but I guess it's outdated.

@golang golang locked and limited conversation to collaborators Nov 2, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants