Wraparound with modulo or iterator?

Hi all!
I recently had a use case for cycling over the letters A to Z for a project. From what I found so far this is usually done with a modulo-based approach which I did like this:

let mut counter: u8 = 0;
for line in parse_lines() {
    match line {
        foo => counter += 1,
        bar => {
                  let chain_id = std::str::from_utf8(&[65 + (chain_counter % 26)])
                           .expect("Parsing failed").to_string();
                  // do stuff with chain_id
        }
    }
}

Although I already kept it quite simple this seems less legible to me than an approach based on an iterator:

let mut iter = ('A'..='Z').cycle();
// Initialize first value
iter.next();
for line in parse_lines() {
    match line {
        foo => iter.next(),
        bar => {
                  let chain_id = iter.unwrap().to_string();
                  // do stuff with chain_id
        }
    }
}

In my context the loop is run through a lot and the above code would be executed many times. I'm thinking the exact approach doesn't matter too much here since both seem to work and, as far as I can see, no unnecessary allocations should happen either way.
Is there something obvious I'm missing here?

Missing with regards to what? I don't really understand what your question is.

I was wondering if there would be a preference for either approach in terms of performance or whether it doesn't matter.
I'm leaning towards the iterator approach because I find it more clear but I thought I might be missing something why that isn't a good idea.

Go with the more readable, simpler approach first. Iterators are there for you to use them. I don't think there should be a performance difference, but as always, guessing about performance is futile. If you find that your code is too slow, measure.

1 Like

Not sure what'd faster. Checking the iterator end (which cycle needs to do) may be an extra conditional in the compiled code, but the modulo-operation might be more expensive anyway. I'd use the iterator approach and would assume it is faster, but I'm not an expert. Maybe it's possible to look at the machine code and compare? It may also depend on the platform and particular CPU.

Ok, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.