Chase Mao's blog

Go Performance loss when using reflection to invoke functions

2024-03-20

Conclusion: calling functions through reflection in Go is about 1000 times slower than calling them directly. Pre-saving the reflection objects of functions has almost no impact on performance, as the time-consuming part is concentrated in calling the Call method of the reflection objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
func f() {}

func BenchmarkDirect(b *testing.B) {
	for i := 0; i < b.N; i++ {
		f()
	}
}

func BenchmarkReflectOnlyRun(b *testing.B) {
	fv := reflect.ValueOf(f)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		fv.Call(nil)
	}
}

func BenchmarkReflect(b *testing.B) {
	for i := 0; i < b.N; i++ {
		fv := reflect.ValueOf(f)
		fv.Call(nil)
	}
}

Output is

1
2
3
4
5
6
# -benchmem flag provide info of heap memory allocation
$ go test -bench . -benchmem

BenchmarkDirect                 1000000000           0.2425 ns/op
BenchmarkReflectOnlyRun         100000000            107.8 ns/op
BenchmarkReflect                100000000            108.9 ns/op