Speed up Write data from vector vec_01 to vec_02

The first version of the code works faster.
For vectors with the number of elements equal to 100_000_000
I have 26.2037 ms vs 39.9429 ms
Is there a faster way?

[1]
fn main() {
   //
   let vec_01: Vec<u8> = vec![3, 5, 7];
   let mut vec_02: Vec<u8> = vec![0; 3];
   //
   println!("vec_01 = {:?}", &vec_01);
   println!("vec_02 = {:?}", &vec_02);
   //
   let mut j: usize = 0;
   loop {
      if j == 3 {break};
      vec_02[j] = vec_01[j];
      j = j + 1;   
   }
   //
   println!("\nvec_01 = {:?}", &vec_01);
   println!("vec_02 = {:?}", &vec_02);   
}
[2]
fn main() {
   //
   let vec_01: Vec<u8> = vec![3, 5, 7];
   let mut vec_02: Vec<u8> = vec![0; 3];
   //
   println!("vec_01 = {:?}", &vec_01);
   println!("vec_02 = {:?}", &vec_02);
   //
   {
    vec_02 = vec_01.clone();
   }
   //
   println!("\nvec_01 = {:?}", &vec_01);
   println!("vec_02 = {:?}", &vec_02);   
}

I doing it right?
Is it possible to speed up writing data
from vec_01 to vec_02
in a separate scope?

1 Like

Considering you just need the first item in the vector i think instead of using loop you can just directly assign the first element like ...
vec_02[0] = vec_01[0];
I'm new to rust tho i am up for corrections thanks:)

In the second case you're creating the 2nd vec twice, once at the top and then once when you clone. And in the first case you're breaking out of the loop after only one element (of three) is copied.

Please make sure you're showing the actual code snippets that you're using in your test.

1 Like

in the first case you're breaking out of the loop after only one element

I fixed the code, thanks

j == 3
thanks

1 Like

When cloning, do not create a vec filled with zeros first. By creating the vec filled with zeros first, you are creating the new vec twice. The Vec::clone method creates a new vec.

1 Like

What if I want to work with vec_02 before the scope

where I write data

{
vec_02 = ...;
}

and after?
can't transmit &mut vec_02

If you always have a preexisting vec_02 and you want to replace its elements, do not use clone -- clone allocates a new vec. That's why it is slower.

To copy between two existing vecs, use copy_from_slice:

vec_02.copy_from_slice(&vec_01);
1 Like

Also, be sure to build and run the test using --release. Without this flag you are using a debug build. Performance testing with a debug build is meaningless because no optimization is performed.

1 Like

thanks, that's what I'm doing

cargo run --release

from `vec_01` to `vec_02`  
       100_000_000 elements
       300 repetitions
time_min = 100 ns time_max = 800 ns

cool, thank you very much.

1 Like

You're welcome.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.