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
This commit is contained in:
David Hill 2014-03-20 13:14:38 -04:00
parent 2de1b73d12
commit b6e6fc25db
2 changed files with 4 additions and 4 deletions

View file

@ -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 // Encode the header for the message. This is done to a buffer
// rather than directly to the writer since writeElements doesn't // rather than directly to the writer since writeElements doesn't
// return the number of bytes written. // return the number of bytes written.
var hw bytes.Buffer hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize))
writeElements(&hw, hdr.magic, command, hdr.length, hdr.checksum) writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum)
// Write header. // Write header.
n, err := w.Write(hw.Bytes()) n, err := w.Write(hw.Bytes())

View file

@ -157,9 +157,9 @@ func (msg *MsgTx) TxSha() (ShaHash, error) {
// cause a run-time panic. Also, SetBytes can't fail here due to the // cause a run-time panic. Also, SetBytes can't fail here due to the
// fact DoubleSha256 always returns a []byte of the right size // fact DoubleSha256 always returns a []byte of the right size
// regardless of input. // regardless of input.
var buf bytes.Buffer buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))
_ = msg.Serialize(buf)
var sha ShaHash var sha ShaHash
_ = msg.Serialize(&buf)
_ = sha.SetBytes(DoubleSha256(buf.Bytes())) _ = sha.SetBytes(DoubleSha256(buf.Bytes()))
// Even though this function can't currently fail, it still returns // Even though this function can't currently fail, it still returns