Skip to content

Commit

Permalink
AccountSharedData::reserve: remove extra alloc + memcpy
Browse files Browse the repository at this point in the history
Calling data_mut().reserve(additional) used to result in _two_ allocs
and memcpys: the first to unshare the underlying vector, and the second
upon calling reserve since Arc::make_mut clones so it uses capacity ==
len.

With this fix we manually "unshare" allocating with capacity = len +
additional, therefore saving on extra alloc and memcpy.
  • Loading branch information
alessandrod committed May 6, 2024
1 parent a645d07 commit f8969b7
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion sdk/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,13 @@ impl AccountSharedData {
}

pub fn reserve(&mut self, additional: usize) {
self.data_mut().reserve(additional)
if let Some(data) = Arc::get_mut(&mut self.data) {
data.reserve(additional)
} else {
let mut data = Vec::with_capacity(self.data.len().saturating_add(additional));
data.extend_from_slice(&self.data);
self.data = Arc::new(data);
}
}

pub fn capacity(&self) -> usize {
Expand Down

0 comments on commit f8969b7

Please sign in to comment.