Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping over char[] or substring(): Efficiency in C#?

Tags:

performance

c#

does any of you know what would be better:

a. get a string s, convert to char array and loop over it, or

b. get a string s, loop over substrings of it (s.Substring(i, 1))?

Any tips much appreciated.

like image 855
Dervin Thunk Avatar asked Feb 07 '26 04:02

Dervin Thunk


1 Answers

Option b), looping over substrings, is very inefficient.

The fastest method would be

c) loop over the string chars directly, using the read-only indexer property:

for (int i = 0; i < s.Length; i++) { char c = s[i]; ... }

or, based on the IEnumerable<char> interface:

foreach(char c in s) { ... }
like image 56
Henk Holterman Avatar answered Feb 08 '26 20:02

Henk Holterman