C# Programming Performance Tips - String Split

C# Programming Performance Tips - String Split

You can read all the C# performance tips from the following links,

  1. C# Programming Performance Tips - Part One - String Split
  2. C# Programming Performance Tips - Part Two - String Equals
  3. C# Programming Performance Tips - Part Three - Adding Strings
  4. C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
  5. C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
  6. C# Programming Performance Tips - Part Six - Array Length

C# has a total of 10 overload methods.

C# Programming Performance Tips - img1.png

Most of the developers adopt the below approach.

string str = "Akshay|Patel";  
Stopwatch s1 = new Stopwatch();  
s1.Start();  
string[] temp1 = str.Split('|');  
Console.WriteLine(s1.ElapsedTicks.ToString());

Let’s change the approach; i.e., rather than passing the character directly, let us create an array of characters and pass them as array elements.

Stopwatch s2 = new Stopwatch();  
s2.Start();  
string[] temp = str.Split(new char[] {  
    '|'  
});  
Console.WriteLine(s2.ElapsedTicks.ToString());

Run the application and compare the execution time.

C# Programming Performance Tips - img2.png

The result suggests adopting the second approach to save the execution time.