What is the Fastest Way to Check for a Keyword in a List of Keywords in Delphi?
Posted
by lkessler
on Stack Overflow
See other posts from Stack Overflow
or by lkessler
Published on 2010-01-23T23:54:15Z
Indexed on
2010/04/22
15:43 UTC
Read the original article
Hit count: 342
I have a small list of keywords. What I'd really like to do is akin to:
case MyKeyword of
'CHIL': (code for CHIL);
'HUSB': (code for HUSB);
'WIFE': (code for WIFE);
'SEX': (code for SEX);
else (code for everything else);
end;
Unfortunately the CASE statement can't be used like that for strings.
I could use the straight IF THEN ELSE IF construct, e.g.:
if MyKeyword = 'CHIL' then (code for CHIL)
else if MyKeyword = 'HUSB' then (code for HUSB)
else if MyKeyword = 'WIFE' then (code for WIFE)
else if MyKeyword = 'SEX' then (code for SEX)
else (code for everything else);
but I've heard this is relatively inefficient.
What I had been doing instead is:
P := pos(' ' + MyKeyword + ' ', ' CHIL HUSB WIFE SEX ');
case P of
1: (code for CHIL);
6: (code for HUSB);
11: (code for WIFE);
17: (code for SEX);
else (code for everything else);
end;
This, of course is not the best programming style, but it works fine for me and up to now didn't make a difference.
So what is the best way to rewrite this in Delphi so that it is both simple, understandable but also fast?
(For reference, I am using Delphi 2009 with Unicode strings.)
Followup:
Toby recommended I simply use the If Then Else construct. Looking back at my examples that used a CASE statement, I can see how that is a viable answer. Unfortunately, my inclusion of the CASE inadvertently hid my real question.
I actually don't care which keyword it is. That is just a bonus if the particular method can identify it like the POS method can. What I need is to know whether or not the keyword is in the set of keywords.
So really I want to know if there is anything better than:
if pos(' ' + MyKeyword + ' ', ' CHIL HUSB WIFE SEX ') > 0 then
The If Then Else equivalent does not seem better in this case being:
if (MyKeyword = 'CHIL') or (MyKeyword = 'HUSB') or (MyKeyword = 'WIFE')
or (MyKeyword = 'SEX') then
In Barry's comment to Kornel's question, he mentions the TDictionary Generic. I've not yet picked up on the new Generic collections and it looks like I should delve into them. My question here would be whether they are built for efficiency and how would using TDictionary compare in looks and in speed to the above two lines?
In later profiling, I have found that the concatenation of strings as in: (' ' + MyKeyword + ' ') is VERY expensive time-wise and should be avoided whenever possible. Almost any other solution is better than doing this.
© Stack Overflow or respective owner