Cache homedir between invocations.
The homedir of a user doesn't change anyway. Massively speeds up the
case where $HOME isn't set.
Before: BenchmarkDir 1000 2571286 ns/op
After: BenchmarkDir 1000000000 2.77 ns/op
diff --git a/homedir.go b/homedir.go
index 2f0c5d8..8d87de7 100644
--- a/homedir.go
+++ b/homedir.go
@@ -9,17 +9,30 @@
"strings"
)
+var homedir string
+
// Dir returns the home directory for the executing user.
//
// This uses an OS-specific method for discovering the home directory.
// An error is returned if a home directory cannot be detected.
func Dir() (string, error) {
- if runtime.GOOS == "windows" {
- return dirWindows()
+ if homedir != "" {
+ return homedir, nil
}
- // Unix-like system, so just assume Unix
- return dirUnix()
+ var err error
+ if runtime.GOOS == "windows" {
+ homedir, err = dirWindows()
+ } else {
+ // Unix-like system, so just assume Unix
+ homedir, err = dirUnix()
+ }
+
+ if err != nil {
+ return "", err
+ }
+
+ return homedir, nil
}
// Expand expands the path to include the home directory if the path