DEV Community

ynwd
ynwd

Posted on

Measuring mutex, channel and waitGroup performance

function concurrency
getText no
getTextWithChannel yes
getTextWithWaitGroup yes
getTextWithMutex yes

Source code:

package main

import (
    "fmt"
    "sync"
    "time"
)

func getText() string {
    i := "hi"

    func() {
        i = "hello"
    }()

    return i
}

func getTextWithWaitGroup() string {
    t := "hi"
    var waitgroup sync.WaitGroup
    waitgroup.Add(1)

    go func() {
        t = "hello"
        waitgroup.Done()
    }()

    waitgroup.Wait()
    return t

}

func getTextWithChannel() string {
    t := "hi"
    done := make(chan bool)

    go func() {
        t = "hello"
        done <- true
    }()

    <-done
    return t
}

func getTextWithMutex() string {
    i := text{txt: "hi"}
    go func() {
        i.Set("hello")
    }()
    return i.Get()
}

type text struct {
    txt   string
    mutex sync.Mutex
}

func (t *text) Set(txt string) {
    t.mutex.Lock()
    defer t.mutex.Unlock()
    t.txt = txt
}

func (t *text) Get() string {
    t.mutex.Lock()
    defer t.mutex.Unlock()
    return t.txt
}

Enter fullscreen mode Exit fullscreen mode

Benchmark test:

package main

import "testing"

func BenchmarkGetText(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getText()
    }
}

func BenchmarkGetTextWithChannel(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getTextWithChannel()
    }
}

func BenchmarkGetTextWithWaitGroup(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getTextWithWaitGroup()
    }
}

func BenchmarkGetTextWithMutex(b *testing.B) {
    for i := 0; i < b.N; i++ {
        getTextWithMutex()
    }
}

Enter fullscreen mode Exit fullscreen mode

Result:

Running tool: /usr/local/go/bin/go test -benchmem -run=^$ -coverprofile=/var/folders/43/sjvtz21j0kq56_7vc9nchb400000gq/T/vscode-goeIm86z/go-code-cover -bench . github.com/ynwd/monorepo/Documents/apps/cms/cmd

goos: darwin
goarch: amd64
pkg: github.com/ynwd/monorepo/Documents/apps/cms/cmd
cpu: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
BenchmarkGetText-8                  1000000000           0.5197 ns/op          0 B/op          0 allocs/op
BenchmarkGetTextWithChannel-8        1826163           644.4 ns/op       136 B/op          3 allocs/op
BenchmarkGetTextWithWaitGroup-8      1780219           670.9 ns/op        56 B/op          3 allocs/op
BenchmarkGetTextWithMutex-8          3833086           311.2 ns/op        40 B/op          2 allocs/op
PASS
coverage: 100.0% of statements
ok      github.com/ynwd/monorepo/Documents/apps/cms/cmd 6.332s
Enter fullscreen mode Exit fullscreen mode

Top comments (0)