Skip to content

Commit

Permalink
refactor: optimize Vec push avoid realloc mem (#1374)
Browse files Browse the repository at this point in the history
* optimize Vec push avoid realloc mem

* opt vec alloc in nft transfer execute

* chore: add changelog

* nit in changelog

---------

Co-authored-by: Ranadeep Biswas <[email protected]>
Co-authored-by: Farhad Shabani <[email protected]>
  • Loading branch information
3 people authored Nov 12, 2024
1 parent 34befe5 commit e0451ae
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- [ibc-app-nft-transfer] Preallocate `Vec` to avoid reallocation of memory
([\#1374](https://github.com/cosmos/ibc-rs/pull/1374)).
2 changes: 1 addition & 1 deletion ibc-apps/ics721-nft-transfer/src/handler/on_recv_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ where
};

let mut extras = ModuleExtras {
events: vec![],
events: Vec::with_capacity(data.token_ids.0.len()),
log: Vec::new(),
};
for (i, token_id) in data.token_ids.0.iter().enumerate() {
Expand Down
18 changes: 10 additions & 8 deletions ibc-apps/ics721-nft-transfer/src/handler/send_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,11 @@ where
// overwrite even if they are set in MsgTransfer
if let Some(uris) = &mut packet_data.token_uris {
uris.clear();
uris.reserve_exact(token_ids.0.len());
}
if let Some(data) = &mut packet_data.token_data {
data.clear();
data.reserve_exact(token_ids.0.len());
}
for token_id in token_ids.as_ref() {
if is_sender_chain_source(msg.port_id_on_a.clone(), msg.chan_id_on_a.clone(), class_id) {
Expand All @@ -197,14 +199,14 @@ where
let nft = transfer_ctx.get_nft(class_id, token_id)?;
// Set the URI and the data if both exists
if let (Some(uri), Some(data)) = (nft.get_uri(), nft.get_data()) {
match &mut packet_data.token_uris {
Some(uris) => uris.push(uri.clone()),
None => packet_data.token_uris = Some(vec![uri.clone()]),
}
match &mut packet_data.token_data {
Some(token_data) => token_data.push(data.clone()),
None => packet_data.token_data = Some(vec![data.clone()]),
}
packet_data
.token_uris
.get_or_insert_with(|| Vec::with_capacity(token_ids.0.len()))
.push(uri.clone());
packet_data
.token_data
.get_or_insert_with(|| Vec::with_capacity(token_ids.0.len()))
.push(data.clone());
}
}

Expand Down
1 change: 1 addition & 0 deletions ibc-derive/src/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ fn split_for_impl(
let mut predicates = vec![];

if let syn::PathArguments::AngleBracketed(gen) = args {
generics.reserve_exact(gen.args.len());
for arg in gen.args {
match arg.clone() {
GenericArgument::Type(_) | GenericArgument::Lifetime(_) => {
Expand Down

0 comments on commit e0451ae

Please sign in to comment.