0

I'm not really a programmer and very new to Rust so I assume I'm doing something wrong here. While sorting an array of 1M bytes my Rust function takes 3.5s and the C function only takes 0.2s. This is too big difference for me to believe that Rust is just that much slower. Need sanity check of my code please, what am I missing? I tried replacing the Rust swap function call with directly swapping values like I have done in the C implementation but it makes run even slower.

Rust implementation:

fn sort_bubble(sample: &mut Vec<u8>) -> &mut Vec<u8> {
    let mut updated = true;
    let sample_len = sample.len();
    let mut i;

    while updated {
        i = 0;
        updated = false;
        while i < sample_len - 1 {
            if sample[i + 1] < sample[i] {
                sample.swap(i, i + 1);
                updated = true;
            }
            i += 1;
        }
    }

    sample
}

C implementation:

u_int8_t* sort_bubble(u_int8_t* sample, int sample_len)
{
    char updated = 1;

    while(updated) {
        int i = 0;
        updated = 0;
        while(i < sample_len - 1) {
            if(sample[i + 1] < sample[i]) {
                u_int8_t _ = sample[i];
                sample[i] = sample[i + 1];
                sample[i + 1] = _;
                updated = 1;
            }
            i++;
        }
    }

    return sample;
}
vallentin
  • 23,478
  • 6
  • 59
  • 81
ccie18643
  • 35
  • 4
  • 5
    Did you remember to compile in release mode? – user4815162342 Dec 18 '20 at 22:55
  • 2
    Remember to compile in release mode and benchmark the binary directly, not including overhead from `cargo run` – Ivan C Dec 18 '20 at 23:14
  • I'll recompile and check again, thanks for hint – ccie18643 Dec 19 '20 at 00:11
  • 1
    @tadman u missing the point completely, please read with understanding – ccie18643 Dec 19 '20 at 00:13
  • 2
    Note also [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/3650362) -- while this does not always apply to `&mut` references, it does in your case. There is no reason for `sort_bubble` to also return its input, so the most idiomatic signature for this would be `fn sort_bubble(sample: &mut [u8])`. This is also the signature of the [`sort` method on slices](https://doc.rust-lang.org/std/primitive.slice.html#method.sort) – trent Dec 19 '20 at 02:26

0 Answers0