Skip to content

reflect: add Value.Caller to minimise allocations #59499

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions api/next/49340.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pkg reflect, method (*Caller) Call([]Value, []Value) #49340
pkg reflect, method (*Caller) CallSlice([]Value, []Value) #49340
pkg reflect, method (*Caller) Type() Type #49340
pkg reflect, method (Value) Caller() *Caller #49340
pkg reflect, type Caller struct #49340
29 changes: 29 additions & 0 deletions src/reflect/all_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8410,3 +8410,32 @@ func TestClear(t *testing.T) {
})
}
}

func TestCaller_CallReusesOutValues(t *testing.T) {
fn := func() int {
return 27
}

var i int
v := ValueOf(&i).Elem()
out := []Value{v}

ValueOf(fn).Caller().Call([]Value{}, out)

if i != 27 {
t.Errorf("unexpected result for output value; got %d, want 27", i)
}
}

func TestCaller_CallAllocations(t *testing.T) {
fn := func() int {
return 27
}
c := ValueOf(fn).Caller()

out := make([]Value, c.Type().NumOut())

noAlloc(t, 100, func(int) {
c.Call([]Value{}, out)
})
}
24 changes: 24 additions & 0 deletions src/reflect/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,19 @@ func BenchmarkCall(b *testing.B) {
})
}

func BenchmarkCallerCall(b *testing.B) {
fv := ValueOf(func(a, b string) {})
c := fv.Caller()
out := make([]Value, c.Type().NumOut())
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
args := []Value{ValueOf("a"), ValueOf("b")}
for pb.Next() {
c.Call(args, out)
}
})
}

type myint int64

func (i *myint) inc() {
Expand All @@ -213,6 +226,17 @@ func BenchmarkCallMethod(b *testing.B) {
}
}

func BenchmarkCallerCallMethod(b *testing.B) {
b.ReportAllocs()
z := new(myint)

v := ValueOf(z.inc)
c := v.Caller()
for i := 0; i < b.N; i++ {
c.Call(nil, nil)
}
}

func BenchmarkCallArgCopy(b *testing.B) {
byteArray := func(n int) Value {
return Zero(ArrayOf(n, TypeOf(byte(0))))
Expand Down
Loading