samedi 22 octobre 2022

|Rust| What's the most performant way of initializing a BIG and RANDOMIZED array?

*Note i'm using the 'rand' crate.

I'm new to rust and through some research and testing I was able to find two solutions to this:

#1: This on initializes an array and then populates it with random values:

type RandomArray = [usize; 900]; 

pub fn make_array() -> RandomArray {

    let mut rng = thread_rng();
    
    let mut arr: RandomArray = [0; 900];
        
    for i in 0..900 {
        //I need a range of random values!
        arr[i] = rng.gen_range(0..900)
    }

    arr
}

#2: This one initializes an array, it populates it with values from 0 to 900 and then shuffles it:

type RandomArray = [usize; 900]; 

pub fn make_shuffled_array() -> RandomArray  {
    let mut rng = thread_rng();
    
    let mut arr: RandomArray = [0; 900];
        
    for i in 0..900 {
        arr[i] = i;
    }

    arr.shuffle(&mut rng);

    arr
}

Through my testing, it seems like '#1' is slower but more consistent. But none of these actually initializes the array with the random range of numbers.

Both of these seem to be pretty fast and simple, however, I'm sure that there is an even faster way of doing this.




Aucun commentaire:

Enregistrer un commentaire