[Golang] Test Performance Function Standard - 1
Table of contents
Comparing performance
return error
- create file return.go
func newErr() error {
return errors.new("this is error")
}
func fmtErr() error {
return fmt.Errorf("this is error")
}
- create file return_test.go
func BenchmarkNewErr(b *testing.B) {
for i := 0; i < b.N; i++ {
newErr()
}
}
func BenchmarkFmtErr(b *testing.B) {
for i := 0; i < b.N; i++ {
fmtErr()
}
}
- run:
go test -bench=. -count=5
- Output:
goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i5-10505 CPU @ 3.20GHz
BenchmarkNewErr-12 1000000000 0.2478 ns/op
BenchmarkNewErr-12 1000000000 0.2260 ns/op
BenchmarkNewErr-12 1000000000 0.2342 ns/op
BenchmarkNewErr-12 1000000000 0.2352 ns/op
BenchmarkNewErr-12 1000000000 0.2287 ns/op
BenchmarkFmtErr-12 13758192 114.9 ns/op
BenchmarkFmtErr-12 13655595 102.3 ns/op
BenchmarkFmtErr-12 12359242 99.00 ns/op
BenchmarkFmtErr-12 13170003 86.94 ns/op
BenchmarkFmtErr-12 12656886 85.36 ns/op
-> errors.New() faster fmt.Errorf()
Convert Int to String
create file convert.go
func MethodInt(i int) string { return strconv.FormatInt(int64(i), 10) } func MethodItoa(i int) string { return strconv.Itoa(i) } func MethodFmt(i int) string { return fmt.Sprintf("%d", i) }
create file convert_test.go, copy all below code.
func BenchmarkFmt(b *testing.B) { // TODO: Initialize number := 10 for i := 0; i < b.N; i++ { // TODO: Your Code Here MethodFmt(number) } } func BenchmarkMethodInt(b *testing.B) { // TODO: Initialize number := 10 for i := 0; i < b.N; i++ { // TODO: Your Code Here MethodInt(number) } } func BenchmarkMethodItoa(b *testing.B) { // TODO: Initialize number := 10 for i := 0; i < b.N; i++ { // TODO: Your Code Here MethodItoa(number) } }
run:
go test -bench-. -count=3
output:
goos: linux goarch: amd64 cpu: Intel(R) Core(TM) i5-10505 CPU @ 3.20GHz BenchmarkFmt-12 23235129 51.74 ns/op BenchmarkFmt-12 23171469 51.51 ns/op BenchmarkFmt-12 23137256 54.24 ns/op BenchmarkMethodInt-12 569711481 2.030 ns/op BenchmarkMethodInt-12 592133842 2.019 ns/op BenchmarkMethodInt-12 595410151 2.027 ns/op BenchmarkMethodItoa-12 595789161 2.020 ns/op BenchmarkMethodItoa-12 584260538 2.035 ns/op BenchmarkMethodItoa-12 487900248 2.076 ns/op
-> function fmt.Sprintf is most slowly.