I recently found out that bytes.nth(i) is waay faster than chars.nth(i) if you want to iterate over a String.
pub fn test(word1: String) {
for i in (0..word1.len()).rev() {
word1.bytes().nth(i);
}
}
// runs in +- 820 microseconds (word1.len() = 42551)
vs
pub fn test(word1: String) {
for i in (0..word1.len()).rev() {
word1.chars().nth(i);
}
}
// runs in +- 17.5 seconds (word1.len() = 42551)
I found the explanation te be because bytes.nth() has time complexity O(1) and chars.nth() has time complexity O(n). But why is this the case?
I also saw a suggestion to instantiate a variable and use the chars.next() / .next_back() like in the example below.
let mut word1_chars = word1.chars();
for i in (0..word1.len()).rev() {
word1_chars.next_back()
}
// runs in +- 600 microseconds (word1.len() = 42551)
I was shocked when I saw this was even faster. I presume there is a logical explanation for all of this so if you know it please share it :).
Thanks in advance
Edit: The times were recorded when building in debug mode. When building them for release there is no difference between bytes().nth() and chars.next() (While chars().nth() is more than 10 000 times slower). Why is there such a "big" difference between bytes().nth() and chars.next() in debug mode but not in release?
--release?)/measure? What exact code did you compare this with?.bytes().nth()and.chars().nth()when trying to iterate over a string backwards?