string s = "abcabcabcabcabc";
var foundIndexes = new List<int>();
The question came from the discussion here. I was simply wondering
How can this:
for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))
foundIndexes.Add(i);
Be better than this :
for (int i = 0; i < s.Length; i++)
if (s[i] == 'a') foundIndexes.Add(i);
EDIT : Where all does the performance gain come from?
I did not observe that using
IndexOfwas any faster than direct looping. Honestly, I don’t see how it could be because each character needs to be checked in both cases. My initial results were this:Edit: After running several more times I’ve noticed that you must run release (ie with optimizations) to see my result above. Without optimizations, the for loop is indeed slower.
The benchmark code: