What is the faster way of trying to find a single character on a String?
What of this code is faster/more efficient? :
Boolean contains = myString.IndexOf("~", StringComparision.InvariantCultureIgnoreCase)!=-1;
or
Boolean contains = myString.IndexOf('~')!=-1;
I think the second because is a single character, but using the invariant culture ignore case comparer is suppo开发者_如何学JAVAsed to be fast too :P
Cheers.
The invariant culture is faster than other cultures, but ordinal comparison is even faster. Making it case insensetive is slower for these settings. So the fastest string comparison setting is StringComparison.Ordinal
.
Searching for a character is about twice as fast as the fastest string search.
The second one is a lot faster. On my machine it take about 340ms to do the first and 34ms to do the second one. So 10 times.
Interestingly using InvariantCulture as opposed to InvariantCultureIgnoreCase is faster and as Guffa pointed out Oridinal is faster still. But not as fast as IndexOf(char) though.
static void Main(string[] args)
{
string myString = "qwertyuipasdfghjklzxcvbnm,.~";
var s = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
Boolean contains = myString.IndexOf("~", StringComparison.InvariantCultureIgnoreCase) != -1;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);
var s2 = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
Boolean contains = myString.IndexOf('~') != -1;
}
s2.Stop();
Console.WriteLine(s2.ElapsedMilliseconds);
Console.ReadLine();
}
the two snippets are not equivalent, use whichever is correct. if you are having performance issues profile.
Write your own microbenchmark. Time the running of 100000 times of each of these. That should give you the answer.
You also can take a look here Optimizing string operations in C#, maybe this also will give you some ideas, of how you can optimize it for your needs.
For what it's worth, the IndexOf(char)
overload will be significantly faster, but you probably won't notice unless you're doing tens-of-thousands-to-millions of these comparisons.
You should use whichever overload is most appropriate for what you're actually trying to do.
If you need a culture-aware and/or case-insensitive comparision then use the appropriate IndexOf
overload and StringComparison
option. In this situation, where you're just searching for the ~
character then it makes most sense to simply use IndexOf('~')
.
精彩评论