views:

199

answers:

2

I'm sorry, didn't know that Length is computed at construction time!!

I got 200 char long string A, 5 char long string B If I do

 int Al = A.length;
 int Bl = B.length;

and compare it -- all seems fine BUT If I do this few million times to calculate something, it's too expensive for the thing I need.

Much simpler and neater way would be some function that can compare two strings and tell me when the other is AT LEAST same as the other. Something like (compare_string_lengths(stringA,stringB) -> where string B must be at least as long (chars) as string A to return TRUE for function.

Yes, I know that the function wouldn't have any idea which string is shorter, but if lengths of the two strings would be counted in parallel so when one exceeds the other, function knows what to "answer".

Thanks for any hints.

+9  A: 

If you only need to know whether the strings differs in length (or if you wish to check whether the lenghts are equal before comparing), I don't think that you can do it faster than comparing the Length property. Retrieving the length from a string is an O(1) operation.

To actually compare the strings you need to look at each character, which makes it an O(n) operation.

Edit:

If things runs too slowly, you should try to have a look in a profiler, what is the slowest parts ? Perhaps it is the construction of your strings that takes the time ?

driis
+1  A: 

There are few things cheaper than comparing the length of two strings.

If you want to find a string in a list of strings, use a Hashtable, like:

    var x = new System.Collections.Generic.Dictionary<string, bool>();
    x.Add("string", true);
    if (x.ContainsKey("string"))
        Console.WriteLine("Found string.");

This is amazingly fast.

Andomar