偽三元表示式 效能分析案例

wdxxl發表於2018-10-08

如何去分析一個 func 的三元表示式的效果比 map 的方式更加效能高? Q1: benchmark 好像也看不出什麼,可能例子太簡單的原因?感謝 樓下朋友指出問題哈 Q2 string 物件和 interface 斷言居然也沒什麼消耗差距。

package main

import "testing"

func ternary(x int) string {
    if x > 0 {
        return "a"
    }
    return "b"
}

func TernaryInterface(statement bool, a, b interface{}) interface{} {
    if statement {
        return a
    }
    return b
}

func BenchmarkTernaryInterface(b *testing.B) {
    var y string
    for i := 0; i < b.N; i++ {
        y = TernaryInterface(1 > 0, "a", "b").(string)
    }
    _ = y
}
func BenchmarkTernaryWithFunc1(b *testing.B) {
    var y string
    for i := 0; i < b.N; i++ {
        y = ternary(1)
    }
    _ = y
}
func BenchmarkTernaryMap1(b *testing.B) {
    var y string
    for i := 0; i < b.N; i++ {
        y = map[bool]string{true: "a", false: "b"}[1 > 0]
    }
    _ = y
}

go test -bench=. -benchmem -cpu 1,2,4,8
goos: darwin
goarch: amd64
BenchmarkTernaryInterface       2000000000         0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryInterface-2     2000000000        0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryInterface-4     2000000000        0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryInterface-8     2000000000        0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryWithFunc1       2000000000       0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryWithFunc1-2     2000000000      0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryWithFunc1-4     2000000000      0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryWithFunc1-8     2000000000      0.32 ns/op            0 B/op          0 allocs/op
BenchmarkTernaryMap1            20000000              103 ns/op               0 B/op          0 allocs/op
BenchmarkTernaryMap1-2          20000000             104 ns/op               0 B/op          0 allocs/op
BenchmarkTernaryMap1-4          20000000             102 ns/op               0 B/op          0 allocs/op
BenchmarkTernaryMap1-8          20000000             102 ns/op               0 B/op          0 allocs/op
PASS
更多原創文章乾貨分享,請關注公眾號
  • 偽三元表示式 效能分析案例
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章