Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7bcd66c

Browse files
committed
assert.Empty: refactor using reflect.Value.IsZero()
Simplify isEmptyValue (used by assert.Empty) by checking early if the value is the zero value of the type using reflect.Value.IsZero (available since Go 1.13, so after the initial assert.Empty implementation). isEmpty is now faster. go test -bench Benchmark_isEmpty goos: darwin goarch: arm64 pkg: github.com/stretchr/testify/assert cpu: Apple M2 Before: Benchmark_isEmpty-8 15841243 77.27 ns/op 8 B/op 1 allocs/op After Benchmark_isEmpty-8 50665512 21.08 ns/op 0 B/op 0 allocs/op
1 parent 43eb300 commit 7bcd66c

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

assert/assertions.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -757,22 +757,20 @@ func isEmpty(object interface{}) bool {
757757

758758
// isEmptyValue gets whether the specified reflect.Value is considered empty or not.
759759
func isEmptyValue(objValue reflect.Value) bool {
760+
if objValue.IsZero() {
761+
return true
762+
}
763+
// Special cases of non-zero values that we consider empty
760764
switch objValue.Kind() {
761765
// collection types are empty when they have no element
766+
// Note: array types are empty when they match their zero-initialized state.
762767
case reflect.Chan, reflect.Map, reflect.Slice:
763768
return objValue.Len() == 0
764-
// pointers are empty if nil or if the value they point to is empty
769+
// non-nil pointers are empty if the value they point to is empty
765770
case reflect.Ptr:
766-
if objValue.IsNil() {
767-
return true
768-
}
769771
return isEmptyValue(objValue.Elem())
770-
// for all other types, compare against the zero value
771-
// array types are empty when they match their zero-initialized state
772-
default:
773-
zero := reflect.Zero(objValue.Type())
774-
return reflect.DeepEqual(objValue.Interface(), zero.Interface())
775772
}
773+
return false
776774
}
777775

778776
// Empty asserts that the given value is "empty".

0 commit comments

Comments
 (0)