golang defer has an associated performance cost

golang defer keyword doesn't come free. Let's see this in action 

main_test.go 


package main

import (
  "sync"
  "testing"
)

func withoutDefer() {
    mu.Lock()
    // critical section
    mu.Unlock()
}

func withDefer() {
    mu.Lock()
    defer mu.Unlock()
    // critical section
}

var mu sync.Mutex

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

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

} 

Run the following command 

go test -bench=.

Performance results shows that it can be slower as shown here





Comments

Popular posts from this blog

gemini cli getting file not defined error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

vllm : Failed to infer device type