|
||
|
|
#1 (permalink) |
|
Forum Expert
Join Date: Nov 2002
Posts: 630
|
I have a script that needs to run the quickest (most efficient) and Im looking for advice on how to accomplish this.
The script reads a file and finds tags for an object (like creates a monster, then reads possible tags for stats/things to change on the default monster) and currently im looking to make this faster. It reads a line, then checks the first letter of it to see what it is, then does a select case for all letters lower to uppercase. Is there a way I can accomplish this faster? I read that I should be able to do a select case with numbers on it somehow and then just cut it in half (where its like... is the letter above J or not, then go into it some more and if its above S or not, then do a select case on like 10 choices. That is what im looking for but I dont understand how to do the letters-> number part. eg. (line = char line[100]; ) Code:
readline();
switch( line[0] )
{
case 'a':
case 'A':
case 'b':
case 'B':
etc..
default:
}
|
|
|
|
|
|
#2 (permalink) |
|
Forum Expert
|
All letters are actually represented as numbers in the ASCII table, 'A' = 65, 'B' = 66, ..., 'a' = 97, 'b' = 98, ... (however, do note that six punctuation characters come between 'Z' and 'a', that is why 'a' starts on 97 and not on 91).
Thus, rather than having an enormous switch statement (which, by the way, isn't slow by any means; by optimizing you should really mean optimizing your time and not the run time in this case), you could just have an if statement that checks if the value is between 65 and 90 (to check 'A' to 'Z') or if the value is between 97 and 122 (for 'a' to 'z'). Or you could even easier (and more descriptively) check if the value is between 'A' and 'Z' (as in if(line[0] >= 'A' && line[0] <= 'Z') ) since the compiler will treat the letters as if they are their number values when doing so. Naturally, you can do the same with 'a' and 'z'. |
|
|
|
|
|
#3 (permalink) |
|
Forum Expert
Join Date: Nov 2005
Location: San Diego, CA
Posts: 1,824
|
I'm a little unclear on what is trying to be accomplished here.
Giant switch statements can indeed be slow, as they are O(N) over the number of cases in them. I think I'd like a little more information about the objective. A HashTable might be better for you, depending on what you are trying to accomplish. Anyway, one way to speed up a switch statement is to put the most common cases first. So, for example, if "M" is the most common case, put it first, and other elements second. C// |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|