TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# String For Loop, Count Spaces in String

Loop over a string with the for-loop, avoiding creating temporary strings. Count spaces in the string.
String for-loop. For loops over characters in strings. Some code examples use an inefficient string loop pattern. This causes unnecessary allocations on the managed heap. These loops can be improved and simplified.StringsFor
Example. We look at 2 loops over a single string reference's character data. Each loop compares each character in the source string against the space character. The first loop is much faster and results in fewer allocations.

Here: We count spaces in the string with 2 loops. The first version is much faster—it should always be used.

First loop: The first loop checks each char directly. No allocations on the managed heap occur and this is a well-performing loop over the string.

Second loop: The second loop in the program text also uses a for-loop. It calls the ToString method.

ToString

ToString: This requires an allocation of a new string on the managed heap. This loop is slower because it allocate strings.

C# program that uses string for-loop using System; class Program { static void Main() { string input = "The Dev Codes website"; // // Check each character in the string using for-loop. // int spaces1 = 0; for (int i = 0; i < input.Length; i++) { if (input[i] == ' ') { spaces1++; } } // // BAD: Check each character in the string with ToString calls. // int spaces2 = 0; for (int i = 0; i < input.Length; i++) { if (input[i].ToString() == " ") // NO { spaces2++; } } // // Write results. // Console.WriteLine(spaces1); Console.WriteLine(spaces2); } } Output 3 3
Benchmark. The for-loop that uses direct character comparisons is far faster, nearly ten times faster, than the for-loop that invokes the ToString method. After the benchmark results, we note another common string loop mistake.Benchmark
Benchmark description Iterations: 10000000 Input string: "The Dev Codes website" Loop bodies: Same as in top example. Character testing loop: 46.50 ns ToString loop: 445.11 ns Summary: Using ToString was nearly ten times slower.
Also, the ToString loop here has similarities to a pattern occasionally used by developers that loops over the string by taking a one-character substring. This results in a string allocation because it demands a new string reference.

Note: If you are testing characters, you also do not need to do this. Loops that use Substring will be much slower.

Substring
Summary. Chars should be directly tested in string loops. Developers who are accustomed to other languages (like Java) where character iteration is different sometimes make looping mistakes. This is likely due to unfamiliarity.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf