All Benchmarks

Go Benchmark

Interface vs Direct Method Call

Measure the overhead of calling a method through an interface instead of on the concrete type.

interfacestruct

This benchmark compares the performance of interface vs direct method calls in Go. Each benchmark creates a struct, containing a single method. It will then call the method on the struct, either directly or via an interface.

linux/amd64AMD Ryzen 9 9950X3D 16-Core Processorbenchmarks/interface-vs-direct-method-call
Compare atCPUs

1 CPU

Fastest

Interface Method Call

0.23 ns/op

Slowest

Direct Method Call

0.24 ns/op

32 CPUs

Fastest

Interface Method Call

0.25 ns/op

Slowest

Direct Method Call

0.25 ns/op

Performance Comparison (lower is better)
CPU:
#1

Interface Method Call #

Fastest

This benchmark calls the method on the struct via an interface.

CPU Scaling (lower is better)
type Interface interface {
	Method()
}

type InterfaceStruct struct{}

func (m InterfaceStruct) Method() {}

func BenchmarkInterfaceMethodCall_run(b *testing.B) {
	var s Interface = InterfaceStruct{}
	for i := 0; i < b.N; i++ {
		s.Method()
	}
}
1 CPU
1xfaster(4%)thanDirect Method Call
32 CPUs
Same speed asDirect Method Call
#2

Direct Method Call #

Slowest

This benchmark calls the method on the struct directly.

CPU Scaling (lower is better)
type DirectStruct struct{}

func (m DirectStruct) Method() {}

func BenchmarkDirectMethodCall_run(b *testing.B) {
	s := DirectStruct{}
	for i := 0; i < b.N; i++ {
		s.Method()
	}
}
1 CPU
1xslower(4%)thanInterface Method Call
32 CPUs

Contributors