Friday, August 10, 2012

c# - String.StartsWith , StringComparision.Ordinal Performance

I have a daily process that parses a huge file and creates an aggregated output file by reading each line.I wanted to improve the performance of the this process so I decided to visit each string operation in my code and see if I could there was any room for improvement.

I came across this piece of code and it was being executed for each line.The number of lines in the input file varied on a daily basis but was around 20+ million

if (x.StartsWith("a"))
           z = x.Replace("a", "");
else if (x.StartsWith("b"))
           z = x.Replace("b", "");

After reading through string comparisons,performance I decided to test it out in my process
(http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx)

I modified the above code to this


if (x.StartsWith("a", StringComparison.Ordinal))
           z = x.Replace("a", "");
else if (x.StartsWith("b", StringComparison.Ordinal))
           z = x.Replace("b", "");

Indeed there was a 21% performance gain.


Results:


Before


 











After





No comments: