All Benchmarks

Interface vs Direct Method Call — Go Benchmark

A benchmark to compare the performance of interface vs direct method calls in Go.

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 at
CPUs
Performance Comparison (lower is better)
CPU:
1

Interface Method Call

Fastest

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

CPU Scaling — Interface Method Call (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
1×faster(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 — Direct Method Call (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
1×slower(4%)thanInterface Method Call
32 CPUs

Contributors