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

perf(config): refactor atomicValue Bool method by optimizing string handling #3475

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

Conversation

1911860538
Copy link
Contributor

Below is my local benchmark code:

value.go

func (v *atomicValue) Bool() (bool, error) {
	switch val := v.Load().(type) {
	case bool:
		return val, nil
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string:
		return strconv.ParseBool(fmt.Sprint(val))
	}
	return false, v.typeAssertError()
}

func (v *atomicValue) BoolNew() (bool, error) {
	switch val := v.Load().(type) {
	case bool:
		return val, nil
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
		return strconv.ParseBool(fmt.Sprint(val))
	case string:
		return strconv.ParseBool(val)
	}
	return false, v.typeAssertError()
}

value_test.go

func BenchmarkStringBool(b *testing.B) {
	v := &atomicValue{}
	v.Store("true")
	
	b.ReportAllocs()
	b.ResetTimer()
	
	for i := 0; i < b.N; i++ {
		_, err := v.Bool()
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkStringBoolNew(b *testing.B) {
	v := &atomicValue{}
	v.Store("true")

	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		_, err := v.BoolNew()
		if err != nil {
			b.Fatal(err)
		}
	}
}

benchmark output

goos: darwin
goarch: amd64
pkg: github.com/go-kratos/kratos/v2/config
cpu: Intel(R) Core(TM) i7-8569U CPU @ 2.80GHz
BenchmarkStringBool
BenchmarkStringBool-8      	19154788	        60.80 ns/op	       4 B/op	       1 allocs/op
BenchmarkStringBoolNew
BenchmarkStringBoolNew-8   	319886724	         3.709 ns/op	       0 B/op	       0 allocs/op
PASS

Process finished with the exit code 0

@dosubot dosubot bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Nov 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size:XS This PR changes 0-9 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant