Skip to content

Commit 88f777f

Browse files
committed
Add madvise() after mmap().
This commit advises the mmapped data file to use MADV_RANDOM to avoid readahead. This can provide a performance boost to Bolt databases that are larger than memory by avoiding unnecessary disk i/o.
1 parent afceb31 commit 88f777f

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

bolt_unix.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ func mmap(db *DB, sz int) error {
6363
return err
6464
}
6565

66+
// Advise the kernel that the mmap is accessed randomly.
67+
if err := madvise(b, syscall.MADV_RANDOM); err != nil {
68+
return fmt.Errorf("madvise: %s", err)
69+
}
70+
6671
// Save the original byte slice and convert to a byte array pointer.
6772
db.dataref = b
6873
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
@@ -84,3 +89,12 @@ func munmap(db *DB) error {
8489
db.datasz = 0
8590
return err
8691
}
92+
93+
// NOTE: This function is copied from stdlib because it is not available on darwin.
94+
func madvise(b []byte, advice int) (err error) {
95+
_, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
96+
if e1 != 0 {
97+
err = e1
98+
}
99+
return
100+
}

0 commit comments

Comments
 (0)