C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ToStringToString: 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 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.
Note: If you are testing characters, you also do not need to do this. Loops that use Substring will be much slower.
Substring