0

I have a vector X of u32 that I need to access the elements of in a known order. There's another vector orderings containing a list of usize which is the order I need to access the elements of X in.

At the moment I'm doing:

for order in orderings.iter() {
    let val = X[*order];
    //do stuff with val
}

Unfortunately this is pretty slow as I'm having to index into X every single iteration of the loop, is there a way I can just get the val for each loop directly without having to do this indexing that is faster?

Hadi Khan
  • 577
  • 2
  • 8
  • 30
  • What makes you think a single pointer addition + lookup is slow? It's obviously not as fast as reading the values from a slice in sequence but other than maybe doing the lookups ahead of time if you do need them to be in that order multiple times there is really nothing you can improve. – cafce25 Dec 07 '22 at 18:05
  • Yeah there's really no way to avoid indexing. You could avoid the associated bounds check by using [`unsafe fn get_unchecked`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.get_unchecked). Note that you must ensure that all indices in `order` are present in `X`. – PitaJ Dec 07 '22 at 18:06
  • 1
    Why do you think it's the indexing that's slow? – PitaJ Dec 07 '22 at 18:09
  • @PitaJ I got that impression from the answer here: https://stackoverflow.com/questions/51899535/when-should-i-use-direct-access-into-a-rust-vec-instead-of-the-get-method – Hadi Khan Dec 07 '22 at 18:13
  • @cafce25, see my comment to PitaJ – Hadi Khan Dec 07 '22 at 18:13
  • Why doesn't the answer to that question work for you? – cafce25 Dec 07 '22 at 18:18
  • 1
    Indexing bounds checks can cause bottlenecks in some cases, but generally, they are insignificant compared to anything else you're doing. If you're just trying to avoid them because you get the impression that they're slow, then you're probably prematurely optimizing. – PitaJ Dec 07 '22 at 18:19
  • Only if you have benchmarks that prove the bounds checks are the problem, should you dip into unsafe to avoid them. – PitaJ Dec 07 '22 at 18:21
  • @cafce25 if I could get an iterator which produced elements in the order given by `orderings` I would use that, my impetus for asking this question was to find out if such a thing existed. – Hadi Khan Dec 07 '22 at 18:29
  • Even if such thing would exist, it would still use bound checks. – Chayim Friedman Dec 07 '22 at 22:42

0 Answers0