string.StartsWith very, very slow. How suddenly?

  • Thread starter Thread starter Alexander Vasilevsky
  • Start date Start date
A

Alexander Vasilevsky

U. StartWith works 10 times faster than String.StartsWith. What the hell?

U.StartWith: 00:00:00.0259870
String.StartsWith: 00:00:00.2118940

See code below

using System;

namespace ConsoleApplication1
{
class U
{
public static bool StartWith(string pattern, string number)
{
bool match = true;
for (int digitIndex = 0; digitIndex < pattern.Length && match;
digitIndex++)
{
match = match &&
number[digitIndex].Equals(pattern[digitIndex]);
}
return match;
}
}

class Program
{
static void Main(string[] args)
{
const int max = 1000000;

string[] myStrings = new string[max];
string[] patterns = new string[max];
var rnd = new Random();
for (int i = 0; i < max; i++)
{
myStrings = rnd.Next(1000000).ToString("{0:D6}"); // 6
digits
patterns = rnd.Next(1000).ToString(); // 1-3 digits
}

DateTime tU = DateTime.Now;
for (int i = 0; i < max; i++)
{
U.StartWith(patterns, myStrings);
}
Console.WriteLine("U.StartWith: " + (DateTime.Now -
tU).ToString());

DateTime tString = DateTime.Now;
for (int i = 0; i < max; i++)
{
myStrings.StartsWith(patterns);
}
Console.WriteLine("String.StartsWith: " + (DateTime.Now -
tString).ToString());
}
}
}

http://www.alvas.net - Audio tools for C# and VB.Net developers + Christmas
Gift
 
Alexander said:
U. StartWith works 10 times faster than String.StartsWith. What the hell?

U.StartWith: 00:00:00.0259870
String.StartsWith: 00:00:00.2118940
As a little challenge, I'll stop reading your post here. I'm instead making
a prediction: you didn't pass StringComparison.Ordinal to .StartsWith(), so
instead you got a culture-sensitive comparison. By contrast, your custom
comparison routine doesn't take culture into account. Retrying with a
comparison argument will show .StartsWith() to be just as fast or faster
than your custom routine.

Am I right?
 
Jeroen Mostert said:
As a little challenge, I'll stop reading your post here. I'm instead
making a prediction: you didn't pass StringComparison.Ordinal to
.StartsWith(), so instead you got a culture-sensitive comparison. By
contrast, your custom comparison routine doesn't take culture into
account. Retrying with a comparison argument will show .StartsWith() to be
just as fast or faster than your custom routine.

Am I right?


Yes, that makes a huge difference. Also, the routine needs to check if the
string for the pattern is longer than the test string. An error is thrown
if the pattern is longer than your string being searched.
 
Back
Top