Skip to content

Commit 8d438fe

Browse files
[IMPROVED] Reduce allocations in writeMsgRecord (#6576)
The following changes are all to reduce GC pressure: - The `hdr` array looked like it should be stack-allocated but was actually always escaping to the heap because of the highwayhash writer, so instead of allocating a ton of those, just preallocate space on the underlying cache buffer instead (since that has already escaped to the heap); - Reuse the memory of the last checksum instead of allocating unnecessarily there too, and use `stringToBytes` for the subject, avoiding a further copy. Signed-off-by: Neil Twigg <neil@nats.io>
2 parents e938ac0 + 18a2f3b commit 8d438fe

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

server/filestore.go

+5-6
Original file line numberDiff line numberDiff line change
@@ -5714,23 +5714,23 @@ func (mb *msgBlock) writeMsgRecord(rl, seq uint64, subj string, mhdr, msg []byte
57145714
// With headers, high bit on total length will be set.
57155715
// total_len(4) sequence(8) timestamp(8) subj_len(2) subj hdr_len(4) hdr msg hash(8)
57165716

5717-
// First write header, etc.
57185717
var le = binary.LittleEndian
5719-
var hdr [msgHdrSize]byte
57205718

57215719
l := uint32(rl)
57225720
hasHeaders := len(mhdr) > 0
57235721
if hasHeaders {
57245722
l |= hbit
57255723
}
57265724

5725+
// Reserve space for the header on the underlying buffer.
5726+
mb.cache.buf = append(mb.cache.buf, make([]byte, msgHdrSize)...)
5727+
hdr := mb.cache.buf[len(mb.cache.buf)-msgHdrSize : len(mb.cache.buf)]
57275728
le.PutUint32(hdr[0:], l)
57285729
le.PutUint64(hdr[4:], seq)
57295730
le.PutUint64(hdr[12:], uint64(ts))
57305731
le.PutUint16(hdr[20:], uint16(len(subj)))
57315732

57325733
// Now write to underlying buffer.
5733-
mb.cache.buf = append(mb.cache.buf, hdr[:]...)
57345734
mb.cache.buf = append(mb.cache.buf, subj...)
57355735

57365736
if hasHeaders {
@@ -5744,13 +5744,12 @@ func (mb *msgBlock) writeMsgRecord(rl, seq uint64, subj string, mhdr, msg []byte
57445744
// Calculate hash.
57455745
mb.hh.Reset()
57465746
mb.hh.Write(hdr[4:20])
5747-
mb.hh.Write([]byte(subj))
5747+
mb.hh.Write(stringToBytes(subj))
57485748
if hasHeaders {
57495749
mb.hh.Write(mhdr)
57505750
}
57515751
mb.hh.Write(msg)
5752-
checksum := mb.hh.Sum(nil)
5753-
// Grab last checksum
5752+
checksum := mb.hh.Sum(mb.lchk[:0:highwayhash.Size64])
57545753
copy(mb.lchk[0:], checksum)
57555754

57565755
// Update write through cache.

0 commit comments

Comments
 (0)