Skip to content
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

Relax IsEmpty, IsNotEmpty and Coalesce constraint from comparable to any #219

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

CorentinClabaut
Copy link
Contributor

closes #218

@samber
Copy link
Owner

samber commented Jun 28, 2024

Much much slower

import (
	"reflect"
	"testing"
)

func IsEmptyComparable[T comparable](v T) bool {
	var zero T
	return zero == v
}

func IsEmptyReflect[T any](v T) bool {
	return reflect.ValueOf(&v).Elem().IsZero()
}

func BenchmarkMap(b *testing.B) {
	b.Run("IsEmptyComparable(42)", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyComparable(42)
		}
	})
	b.Run("IsEmptyComparable(0)", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyComparable(0)
		}
	})

	b.Run("IsEmptyReflect(42)", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyReflect(42)
		}
	})
	b.Run("IsEmptyReflect(0)", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyReflect(0)
		}
	})

	b.Run("IsEmptyReflect(map[string]int{'foo': 42})", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyReflect(map[string]int{"foo": 42})
		}
	})
	b.Run("IsEmptyReflect(map[string]int{})", func(b *testing.B) {
		for n := 0; n < b.N; n++ {
			_ = IsEmptyReflect(map[string]int{})
		}
	})
}
BenchmarkMap/IsEmptyComparable(42)-10           1000000000               0.3126 ns/op          0 B/op          0 allocs/op
BenchmarkMap/IsEmptyComparable(0)-10            1000000000               0.3143 ns/op          0 B/op          0 allocs/op
BenchmarkMap/IsEmptyReflect(42)-10              273421233                4.374 ns/op           0 B/op          0 allocs/op
BenchmarkMap/IsEmptyReflect(0)-10               274970337                4.491 ns/op           0 B/op          0 allocs/op
BenchmarkMap/IsEmptyReflect(map[string]int{'foo':_42})-10               63943872                18.33 ns/op            0 B/op          0 allocs/op
BenchmarkMap/IsEmptyReflect(map[string]int{})-10                        88390464                13.54 ns/op            0 B/op          0 allocs/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Relax IsEmpty, IsNotEmpty and Coalesce constraint from comparable to any
2 participants