I have a piece of code that's called every few seconds and makes use of an environment variable:
for {
myVar := os.Getenv("MY_VAR")
//Do something
time.Sleep(3 * time.Second)
}
But how costly are repeat calls to os.Getenv
?
The value of the environment variable will not change during runtime, so I could set it as a package level variable:
package blah
var myVar = os.Getenv("MY_VAR")
But this does hurt testability of the code.
Should I set it as a package level variable? Or is os.Getenv
benign enough?
EDIT: I've benchmarked the call to os.Getenv
but is it reliable?
package main_test
import (
"os"
"testing"
)
var result string
func BenchmarkEnv(b *testing.B) {
var r string
for n := 0; n < b.N; n++ {
r = os.Getenv("PATH")
}
result = r
}
goos: darwin
goarch: amd64
BenchmarkEnv-8 20000000 78.7 ns/op
PASS
You can benchmark os.Getenv and see how fast it is.
By looking at its implementation here, it costs: