fatih / color

Color package for Go (golang)
https://pkg.go.dev/github.com/fatih/color
MIT License
7.24k stars 615 forks source link

better performance #94

Closed isayme closed 6 years ago

isayme commented 6 years ago

reduce unnecessary mutex lock if instance already created.

refer: http://marcio.io/2015/07/singleton-pattern-in-go/

Benchmark result: image

Benchmark code

// current getCachedColor func
func getCachedColorCurrent(p Attribute) *Color {
    colorsCacheMu.Lock()
    defer colorsCacheMu.Unlock()

    c, ok := colorsCache[p]
    if !ok {
        c = New(p)
        colorsCache[p] = c
    }

    return c
}

// modified getCachedColor func
func getCachedColorAfter(p Attribute) *Color {
    if c, ok := colorsCache[p]; ok {
        return c
    }

    colorsCacheMu.Lock()
    defer colorsCacheMu.Unlock()

    c, ok := colorsCache[p]
    if !ok {
        c = New(p)
        colorsCache[p] = c
    }

    return c
}

func BenchmarkGetCachedColorCurrent(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getCachedColorCurrent(Underline)
    }
}

func BenchmarkGetCachedColorAfter(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getCachedColorAfter(Underline)
    }
}
isayme commented 6 years ago

close since it has concurrent map read and map write