[Golang] Test Performance - 2

·

1 min read

Comparing the Check If-Else String

package main

import (
    "strings"
    "testing"
)

func CheckIfElseEmpty(s string) string {
    if s == "sdfsdsdfsdsdfsdsdfsdsdfsdsdfsd" {
        return s
    }
    return s
}
func CheckIfElseLen(s string) string {
    if len(s) == 30 {
        return s
    }
    return s
}

func CheckIfElseEqual(s string) string {
    if strings.EqualFold(s, "sdfsdsdfsdsdfsdsdfsdsdfsdsdfsd") {
        return s
    }
    return s
}

func BenchmarkIfElseEmpty(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // TODO: Your Code Here
        CheckIfElseEmpty("sdfsdsdfsdsdfsdsdfsdsdfsdsdfsd")
    }
}

func BenchmarkIfElseEqual(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // TODO: Your Code Here
        CheckIfElseEqual("sdfsdsdfsdsdfsdsdfsdsdfsdsdfsd")
    }
}
func BenchmarkIfElseLen(b *testing.B) {
    for i := 0; i < b.N; i++ {
        // TODO: Your Code Here
        CheckIfElseLen("anc")
    }
}

run cmd: `go test -bench=. -benchmem`:

ducnp@nguyens-MacBook-Pro-2 standard % go test -bench=. -benchmem
goos: darwin
goarch: arm64
pkg: open-dev/performances/standard
BenchmarkIfElseEmpty-8          439244280                2.534 ns/op           0 B/op          0 allocs/op
BenchmarkIfElseEqual-8          27470562                42.45 ns/op            0 B/op          0 allocs/op
BenchmarkIfElseLen-8            1000000000               0.3150 ns/op          0 B/op          0 allocs/op
PASS
ok      open-dev/performances/standard  6.245s
  • Using function check empty is faster than using strings. equal