views:

85

answers:

6

Hi,

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 supposed to be fast too :P

Cheers.

+1  A: 

Write your own microbenchmark. Time the running of 100000 times of each of these. That should give you the answer.

Oded
+2  A: 

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();

    }
Jon Mitchell
+2  A: 

the two snippets are not equivalent, use whichever is correct. if you are having performance issues profile.

jk
"the two snippets are not equivalent" - in which case, what value of myString gives different results?
Joe
+1  A: 

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.

Lukas Šalkauskas
very good article, thanks!
vtortola
no problem :), glad to hear that this helps.
Lukas Šalkauskas
+2  A: 

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.

Guffa
+1  A: 

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('~').

LukeH