Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use Vec::with_capacity avoid realloc memory #1863

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## Cairo-VM Changelog

#### Upcoming Changes
* fix: use Vec::with_capacity avoid realloc memory [#1863](https://github.com/lambdaclass/cairo-vm/pull/1863)

#### [2.0.0-rc0] - 2024-10-22

Expand Down
2 changes: 1 addition & 1 deletion cairo-vm-tracer/src/tracer_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl TracerData {
}
}

let mut memory_accesses: Vec<MemoryAccess> = vec![];
let mut memory_accesses: Vec<MemoryAccess> = Vec::with_capacity(trace.len());
//loop of trace
for entry in trace.iter() {
let run_context = RunContext::new(Relocatable::from((0, entry.pc)), entry.ap, entry.fp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub fn blake2s_compress(
for sigma_list in SIGMA {
state = blake_round(state, message, sigma_list);
}
let mut new_state = Vec::<u32>::new();
let mut new_state = Vec::<u32>::with_capacity(8);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is a bottleneck, it'd make more sense to return an array.

for i in 0..8 {
new_state.push(h[i] ^ state[i] ^ state[8 + i]);
}
Expand Down
4 changes: 2 additions & 2 deletions vm/src/hint_processor/builtin_hint_processor/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ pub fn print_array(
) -> Result<(), HintError> {
print_name(vm, ids_data, ap_tracking)?;

let mut acc = Vec::new();
let arr = get_ptr_from_var_name("arr", vm, ids_data, ap_tracking)?;
let arr_len = get_integer_from_var_name("arr_len", vm, ids_data, ap_tracking)?;
let arr_len = arr_len.to_usize().ok_or_else(|| {
HintError::CustomHint(String::from("arr_len must be a positive integer").into_boxed_str())
})?;
let mut acc = Vec::with_capacity(arr_len);
for i in 0..arr_len {
let val = vm.get_integer((arr + i)?)?;
acc.push(val);
Expand Down Expand Up @@ -109,7 +109,7 @@ pub fn print_dict(
acc.insert(key, DictValue::Int(*value));
}
MaybeRelocatable::RelocatableValue(val) => {
let mut structure = Vec::new();
let mut structure = Vec::with_capacity(pointer_size);
for i in 0..pointer_size {
let val = *vm.get_integer((*val + i)?)?.as_ref();
structure.push(val);
Expand Down
2 changes: 1 addition & 1 deletion vm/src/hint_processor/builtin_hint_processor/usort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn usort_body(
positions_dict.entry(val).or_default().push(i);
}

let mut multiplicities: Vec<usize> = Vec::new();
let mut multiplicities: Vec<usize> = Vec::with_capacity(output.len());
for k in output.iter() {
multiplicities.push(positions_dict[k].len());
}
Expand Down
6 changes: 3 additions & 3 deletions vm/src/serde/serialize_program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ impl From<ProgramSerializer> for ProgramJson {

let mut hints: BTreeMap<usize, Vec<HintParams>> = BTreeMap::new();
for (key, hint_params_vec) in &program_json.hints {
let mut new_hint_params_vec = Vec::new();
let mut new_hint_params_vec = Vec::with_capacity(hint_params_vec.len());
for hint_param in hint_params_vec {
new_hint_params_vec.push(hint_param.clone().into());
}
hints.insert(*key, new_hint_params_vec);
}

let mut reference_manager: ReferenceManager = ReferenceManager {
references: Vec::new(),
references: Vec::with_capacity(program_json.reference_manager.references.len()),
};

for reference in &program_json.reference_manager.references {
Expand Down Expand Up @@ -215,7 +215,7 @@ impl From<&Program> for ProgramSerializer {
let mut hints: BTreeMap<usize, Vec<HintParamsSerializer>> = BTreeMap::new();
for (key, hint_params_vec) in BTreeMap::from(&program.shared_program_data.hints_collection)
{
let mut new_hints_params = Vec::new();
let mut new_hints_params = Vec::with_capacity(hint_params_vec.len());
for hint_params in hint_params_vec {
new_hints_params.push(hint_params.clone().into());
}
Expand Down
2 changes: 1 addition & 1 deletion vm/src/vm/runners/cairo_pie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ pub(super) mod serde_impl {
(segment as usize, offset as usize)
};

let mut res = vec![];
let mut res = Vec::with_capacity(bytes.len().div_ceil(CELL_BYTE_LEN));
for cell_bytes in bytes.chunks(CELL_BYTE_LEN) {
let addr = relocatable_from_bytes(cell_bytes[0..ADDR_BYTE_LEN].try_into().ok()?);
let field_bytes = &cell_bytes[ADDR_BYTE_LEN..CELL_BYTE_LEN];
Expand Down
4 changes: 2 additions & 2 deletions vm/src/vm/vm_memory/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ impl Memory {
/// Gets a range of memory values from addr to addr + size
/// The outputed range may contain gaps if the original memory has them
pub fn get_range(&self, addr: Relocatable, size: usize) -> Vec<Option<Cow<MaybeRelocatable>>> {
let mut values = Vec::new();
let mut values = Vec::with_capacity(size);

for i in 0..size {
values.push((addr + i).ok().and_then(|x| self.get(&x)));
Expand Down Expand Up @@ -555,7 +555,7 @@ impl Memory {
addr: Relocatable,
size: usize,
) -> Result<Vec<Cow<Felt252>>, MemoryError> {
let mut values = Vec::new();
let mut values = Vec::with_capacity(size);

for i in 0..size {
values.push(self.get_integer((addr + i)?)?);
Expand Down
5 changes: 4 additions & 1 deletion vm/src/vm/vm_memory/memory_segments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ impl MemorySegmentManager {
let mut relocation_table = vec![first_addr];
match &self.segment_used_sizes {
Some(segment_used_sizes) => {
relocation_table.reserve_exact(segment_used_sizes.len());
for (i, _size) in segment_used_sizes.iter().enumerate() {
let segment_size = self
.get_segment_size(i)
Expand Down Expand Up @@ -290,8 +291,10 @@ impl MemorySegmentManager {
self.zero_segment_index = self.add().segment_index as usize;
}

let n = size.saturating_sub(self.zero_segment_size);
self.memory.data[self.zero_segment_index].reserve_exact(n);
// Fil zero segment with zero values until size is reached
for _ in 0..(size.saturating_sub(self.zero_segment_size)) {
for _ in 0..(n) {
// As zero_segment_index is only accessible to the segment manager
// we can asume that it is always valid and index direcly into it
self.memory.data[self.zero_segment_index].push(MemoryCell::new(Felt252::ZERO.into()))
Expand Down
Loading