This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The fastest way I know of is simply to loop through the string and see if each character is in the range '0'-'9'. Having tested this before, I know that this is about a thousand times faster than trying and catching a NumberFormatException. (I haven't tested it against regex, however...)
Doing it one or two or ten at a time, it doesn't really matter what method you choose, but if you are parsing a file of thousands of these, performance does become important.
For Regex, jsut check to see if the string matches the pattern [0-9]* [ December 21, 2004: Message edited by: Joel McNary ]
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Trying to check all the characters is not as easy as it sounds. You might need to test for plus and minus signs, ranges from min to max values and so on.
I'd start with the easy parse and catch (or not catch). It might be nice to pass the "int" form around after that so everybody knows it's a valid int. Try-Catch is nearly free as long as you never throw so if your data is almost always good, this is fairly low cost.
If your data may have a lot of errors AND you do thousands of them at a time, the cost of throw & catch is something to think about. But if you do one at a time as the user enters data, the speed difference is nothing to worry about.
Basic advice we repeat often:
Write first for humans to read, second for computers to process. The human time costs more money and the computer is likely to change its algorithms one day and mess up your optimizations.
Don't optimize (sacrifice human readability) until you can prove you have a problem. Get a profiler to show that a method is slow. Then, sometimes, you just gotta get tricky.
Cheers! [ December 22, 2004: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi