From b6e6fc25dbb8bb1a820ddf22ef0e9aead704de1a Mon Sep 17 00:00:00 2001 From: David Hill Date: Thu, 20 Mar 2014 13:14:38 -0400 Subject: [PATCH] Preallocate memory for the message header in WriteMessageN and the serialization buffer in MsgTx's TxSha(). Benchmarking shows this is slightly faster due to avoiding the extra garbage collection in addition to less peak memory usage. Before: BenchmarkTxShaOld 500000 5626 ns/op After: BenchmarkTxShaNew 500000 5457 ns/op --- message.go | 4 ++-- msgtx.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/message.go b/message.go index 98561734..83f51e6f 100644 --- a/message.go +++ b/message.go @@ -218,8 +218,8 @@ func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (in // Encode the header for the message. This is done to a buffer // rather than directly to the writer since writeElements doesn't // return the number of bytes written. - var hw bytes.Buffer - writeElements(&hw, hdr.magic, command, hdr.length, hdr.checksum) + hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize)) + writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum) // Write header. n, err := w.Write(hw.Bytes()) diff --git a/msgtx.go b/msgtx.go index f7cd87d0..61b77c99 100644 --- a/msgtx.go +++ b/msgtx.go @@ -157,9 +157,9 @@ func (msg *MsgTx) TxSha() (ShaHash, error) { // cause a run-time panic. Also, SetBytes can't fail here due to the // fact DoubleSha256 always returns a []byte of the right size // regardless of input. - var buf bytes.Buffer + buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize())) + _ = msg.Serialize(buf) var sha ShaHash - _ = msg.Serialize(&buf) _ = sha.SetBytes(DoubleSha256(buf.Bytes())) // Even though this function can't currently fail, it still returns