> This is very inefficient as statistically it takes n/2 string comparisons.
It's worth noting that if the strings significantly vary in length and composition
most of these string comparisons will short-circuit at the first comparison...
> A much better way is to use a hash table, or a binary find on a sorted list
> of strings. With Delphi, the latter comes "out of the box", in the form of
> TStringList. Sort the contents, and do:
>
> var
> idx: Integer;
> begin
> idx := 0;
> if TStringList.Find (idx, 0) then begin
> TSomeObject(TStringList.Objects[idx]).DoSomething;
> end;
the Stringlist example I gave could have used Sorted := True. Use of the IndexOf
method is still correct as IndexOf checks if the list is sorted and uses find when
it is... The sorting process may be less-efficient than simply using the iterative
search on the unsorted list... Sorting takes nlog(n) comparisons for Quicksort I
believe.
The Find parameters in the above are incorrect and I didn't see any suggestion
in the original question than an associated object was available for each string.
with TStringList.Create do try
commatext := 'hello,goodbye';
Sorted := True; // This may actually slow down the performance.
case IndexOf(MyVar) of
0: Show_Hello;
1: Show_Goodbye;
end;
finally
Free;
end;
Should be the simlpest general use example of a string based case statement - the
efficiency
is poor since the commatext statement must be fully parsed before searching begins but
all this
assumes that the number and length of strings is expected to be relatively short.
The fastest solution I can think of for constant strings would be a packed-trie string
dictionary
stored in a resource with each valid word returning a tag... Searching a trie is
extremely quick
even for large stringlists (it's a popular dictionary storage structure)...
> In theory OO programming never needs a switch statement.
Perhaps at the cost of efficiency... I prefer to see OOP as a structural tool not
an algorithmic paradigm...
--
Aaron Scott-Boddendijk
Jump Productions
(07) 838-3371 Voice
(07) 838-3372 Fax
---------------------------------------------------------------------------
New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
Website: http://www.delphi.org.nz