Why is the performance of generic functions slightly worse in version 1.19?

Code

package main

import (
	"testing"
)

func Add[T int](a, b T) T {
	return a + b
}

func AddInterface(a, b interface{}) interface{} {
	return a.(int) + b.(int)
}

func AddInt(i, j int) int {
	return i + j
}

func BenchmarkAddGeneric(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = Add[int](i, i+1)
	}
}

func BenchmarkAddInterface(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = AddInterface(i, i+1)
	}
}

func BenchmarkAddInt(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = AddInt(i, i+1)
	}
}

go version go1.18.9 darwin/arm64

BenchmarkAddGeneric-10      	1000000000	         0.3187 ns/op
BenchmarkAddInterface-10    	1000000000	         0.3146 ns/op 
BenchmarkAddInt-10          	1000000000	         0.3162 ns/op

go version go1.19.9 darwin/arm64

BenchmarkAddGeneric-10      	1000000000	         0.9443 ns/op
BenchmarkAddInterface-10    	1000000000	         0.3174 ns/op
BenchmarkAddInt-10          	1000000000	         0.3143 ns/op

go version go1.20.5 darwin/arm64

BenchmarkAddGeneric-10      	1000000000	         0.3164 ns/op
BenchmarkAddInterface-10    	1000000000	         0.3152 ns/op
BenchmarkAddInt-10          	1000000000	         0.3162 ns/op

Hi @Ryo,

I can replicate your results, but I have no explanation. I would assume a bug in the runtime or the compiler that got fixed between 1.19.9 and 1.20.5.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.