From 9bf959180b7757fa1f7373e7c16bd224c33db066 Mon Sep 17 00:00:00 2001 From: DanGould Date: Tue, 28 Jun 2022 22:32:39 +0800 Subject: [PATCH] Optimize Witness Serialization We allocated a new vector when serializing a `Witness`. That was inefficient and unnecessary. Use `serialize_seq` to feed the witness elements directly into the serializer. Optimize `Witness` serialization by removing the allocation. --- src/blockdata/witness.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/blockdata/witness.rs b/src/blockdata/witness.rs index c1fa40f4..e9705374 100644 --- a/src/blockdata/witness.rs +++ b/src/blockdata/witness.rs @@ -11,9 +11,6 @@ use crate::prelude::*; use secp256k1::ecdsa; use crate::VarInt; -#[cfg(feature = "serde")] -use serde; - /// The Witness is the data used to unlock bitcoins since the [segwit upgrade](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki) /// /// Can be logically seen as an array of byte-arrays `Vec>` and indeed you can convert from @@ -282,8 +279,15 @@ impl serde::Serialize for Witness { where S: serde::Serializer, { - let vec: Vec<_> = self.to_vec(); - serde::Serialize::serialize(&vec, serializer) + use serde::ser::SerializeSeq; + + let mut seq = serializer.serialize_seq(Some(self.witness_elements))?; + + for elem in self.iter() { + seq.serialize_element(&elem)?; + } + + seq.end() } } #[cfg(feature = "serde")]