Skip to content

Commit

Permalink
perf(tm2/bft/fail): use sync.Once instead of Getenv on each call (#2805)
Browse files Browse the repository at this point in the history
minor change spotted when browsing tm2 code.

fail.Fail is called a lot in hot paths, like in the tm2 state machine.
This avoids calling os.Getenv each time, which actually does a [bunch of
stuff](https://github.com/golang/go/blob/ae8708f7441b24dac126122c5365327d29fa0012/src/syscall/env_unix.go#L69-L88),
even when there is no associated env var.
  • Loading branch information
thehowl committed Sep 18, 2024
1 parent 5503cca commit 6f3a094
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions tm2/pkg/bft/fail/fail.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,33 @@ import (
"fmt"
"os"
"strconv"
"sync"
)

func envSet() int {
func setFromEnv() {
callIndexToFailS := os.Getenv("FAIL_TEST_INDEX")

if callIndexToFailS == "" {
return -1
callIndexToFail = -1
} else {
var err error
callIndexToFail, err := strconv.Atoi(callIndexToFailS)
callIndexToFail, err = strconv.Atoi(callIndexToFailS)
if err != nil {
return -1
callIndexToFail = -1
}
return callIndexToFail
}
}

// Fail when FAIL_TEST_INDEX == callIndex
var callIndex int // indexes Fail calls
var (
callIndex int // indexes Fail calls
callIndexToFail int // index of call which should fail
callIndexToFailOnce sync.Once // sync.Once to set the value of the above
)

// Fail exits the program when after being called the same number of times as
// that passed as the FAIL_TEST_INDEX environment variable.
func Fail() {
callIndexToFail := envSet()
if callIndexToFail < 0 {
return
}
callIndexToFailOnce.Do(setFromEnv)

if callIndex == callIndexToFail {
Exit()
Expand Down

0 comments on commit 6f3a094

Please sign in to comment.