Search code examples
performancerustcompilationreference

References to nested arrays in nested for loops?


I found myself doing something of a habit from Python programming in Rust, in where I saved references to nested objects in larger nested for loops to save some time in indexing the same object unnecessarily over and over. Which got me thinking, with the heavy optimizations at compilation time in Rust, would this even matter, or perhaps, even degrade performance?

Example code:

    let mut arr = [[1; 200]; 200];
    for idx1 in 0..end1 {
      let arr1 = &mut arr[idx1];
      for idx2 in 0..end2 {
        foo(arr1[idx2]);
      }
    }

Edit: Code was wrong as pointed out by @Masklinn!


Solution

  • I found myself doing something of a habit from Python programming in Rust, in where I saved references to nested objects in larger nested for loops to save some time in indexing the same object unnecessarily over and over. Which got me thinking, with the heavy optimizations at compilation time in Rust, would this even matter, or perhaps, even degrade performance?

    Would it matter? Maybe. Rust is bounds-checked so unless the index can be checked at compile-time, indexing has a cost. However that cost may or may not be large compared to the computations they're involved in, and the compiler may or may not be able to lift them out (this would likely depend on the side-effects of the individual iterations).

    Still, that is why Rust code tends to rely heavily on iterators when possible, these only require termination-checking:

       let mut arr = &[[1; 200]; 200];
        for arr1 in arr.iter_mut() {
          for el in arr1.iter_mut() {
            foo(el);
          }
        }
    

    Incidentally your code doesn't really make sense, arr1[idx2] will just return a copy of the value (an i32 by default), and let & mut arr1 = ... is a dereference, that's like writing let arr1 = *....