Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

8
  • Perhaps better to use something like char.IsWhitespace and char.IsControl since I'm assuming they want all white space/non printable removed Commented Jun 26, 2020 at 14:13
  • I cannot agree that for will be more efficient. I would even say that for will be slower due to optimalisation that compiler can do with foreach Commented Jun 26, 2020 at 14:28
  • 1
    @sTrenat - foreach will involve a call to get an an enumerator (probably a struct) and then a call MoveNext for each iteration and a call to Current to get the actual value. The implementation is then just grabbing the character from the specified index. All of this might get optimized away, but it might not. Commented Jun 26, 2020 at 14:31
  • I think you underestimate what compiler optimalisation can do. Check it yourself: dotnetfiddle.net/Gr6knH Commented Jun 26, 2020 at 14:36
  • 1
    @sTrenat switch them around and the results are reversed in favor of for, check it yourself: dotnetfiddle.net/M12Lwh. So in other words, not a good benchmark. Do you have any actual theory/documentation to back this up? Last I know the optimizing the compiler actually does in the case of foreach on an array is iterating instead of using an enumerator, making it almost as fast as for Commented Jun 26, 2020 at 14:40