A simple Go error handling pattern led to 54GB memory usage with 65535 errors

4 months ago 3

65535 errors (with errors.Join + fmt.Errorf ) take 54GB memory

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

package main
import (
"errors"
"fmt"
"os"
)
func main() {
// Create 65535 errors
var errs error
for j := 0; j < 65535; j++ {
newErr := errors.New(fmt.Sprintf("error %d", j))
if errs == nil {
errs = newErr
} else {
errs = errors.Join(newErr, errs)
errs = fmt.Errorf("err %w", errs)
}
}
// Wrap with fmt.Errorf
wrappedErr := fmt.Errorf("got %w", errs)
// Write to file
outputFile, err := os.Create("err1.log")
if err != nil {
panic(err)
}
defer outputFile.Close()
fmt.Fprintln(outputFile, wrappedErr.Error())
}
Read Entire Article