A start read sessions.json whole onto the heap (24.6 MB on a real
history) and decoded it; then each `named` object was copied again by
gjson.ParseBytes before being read. Nothing decoded keeps a byte of
the file: json.Unmarshal, ccStr and unique.Make all copy, and the keys
are cloned.
On unix the file is now mapped read-only and unmapped once decoded (it
is only replaced by a rename, never written in place); elsewhere it is
read as before. `named` parses its bytes in place.
Run:
- go test ./internal/sessions (mica): ok 63s.
- GOOS=darwin/linux/windows go vet ./internal/sessions: ok.
- Broken by hand: read onto the heap again, TestCacheFileReadWithoutACopy
is red ("allocates 688976 bytes; want it mapped"); a key left
pointing into the file (no Clone) faults it with SIGSEGV after the
unmap. The fixture has plain and escaped names, since an escaped one
is unescaped into a copy anyway.
- Every custom UnmarshalJSON in internal/sessions read for bytes it
keeps: none.
- Real account, mote sandbox HOME, start to 50s (pprof alloc_space):
sessions.loadCache 29.5 MB -> 4.4 MB, os.readFileContents 46.7 MB ->
22.0 MB. Footprint peak unchanged (163 to 164 MB); it is set later.
Not tried: a real Linux start; Windows reads the file as before.
34 lines
890 B
Go
34 lines
890 B
Go
//go:build unix
|
|
|
|
package sessions
|
|
|
|
import (
|
|
"os"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
// readCacheFile is the kept parses' file, mapped read-only rather than
|
|
// read onto the heap: a long history's is ~25 MB, held whole while it is
|
|
// decoded at start, and nothing decoded points into it. The file is only
|
|
// replaced by a rename (saveCache), never written in place. done unmaps
|
|
// it; nothing read from it is used after.
|
|
func readCacheFile(path string) (b []byte, done func(), err error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
defer f.Close()
|
|
info, err := f.Stat()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if n := info.Size(); n > 0 && n == int64(int(n)) {
|
|
if b, err := unix.Mmap(int(f.Fd()), 0, int(n), unix.PROT_READ, unix.MAP_SHARED); err == nil {
|
|
return b, func() { unix.Munmap(b) }, nil
|
|
}
|
|
}
|
|
b, err = os.ReadFile(path)
|
|
return b, func() {}, err
|
|
}
|