Re: objective-c / cocoa efficiency
Re: objective-c / cocoa efficiency
- Subject: Re: objective-c / cocoa efficiency
- From: John Stiles <email@hidden>
- Date: Tue, 8 Mar 2005 17:29:24 -0800
On Mar 8, 2005, at 5:22 PM, Jeff Laing wrote:
Um, no, I've seen zillions of programs that do this:
switch (*s) {
case 'a':
if (strcmp(s,"a_command")==0) ...
if (strcmp(s,"another_command")==0) ...
break;
case 'b':
if (strcmp(s,"because")==0) ...
if (strcmp(s,"buggrit")==0) ...
break;
etc...
where doing a switch on the first character in your candidate can
reduce the
number of string comparisons by a factor of 256 (worst case).
If you really have that many strings and want to pick out one of them
quickly, you should put them in a dictionary (i.e. NSDictionary), or
hash table (i.e. unordered_set). A balanced tree (i.e. std::set) would
also be an improvement.
If you want efficiency, switching on the first character and then a
block of strcmp's is really a pretty lame solution. You've just moved
the problem one character deeper into the string—in other words, you're
taking an O(n) problem and just dividing by a constant for an O(n/k)
solution. Why settle for less when there are constant-time (hashing) or
logarithmic-time (tree-based) solutions?
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden