Do rust nested loops need to be avoided for efficiency?

50 Views Asked by At

In Python I am very much aware of avoiding nested loops at all costs. In Rust I am not as careful. However, is it better to try and use zips or iterator tools to avoid nested loops?. Do they gain significant improvements?

The code I have been considering to optimise is the following. It compares and restructures two arrays based on picking individual elements:

fn to_new_vars(&self, new_vars: &Arc<IndexSet<String>>) -> Array2 {
    let indices: Vec<Option<usize>> = new_vars.iter().map(|x| self.vars.get_index_of(x)).collect();

    let mut dual2 = Array::zeros((new_vars.len(), new_vars.len()));
    for (i, row_index) in indices.iter().enumerate() {
        match row_index {
            Some(row_value) => {
                for (j, col_index) in indices.iter().enumerate() {
                    match col_index {
                        Some(col_value) => {dual2[[i, j]] = self.dual2[[*row_value, *col_value]]},
                        None => {}
                    }
                }
            },
            None => {},
        }
    }
    dual2
}
0

There are 0 best solutions below