comparison between recursive w/ onebyone
okay, i wrote the isNum function which checks whether the input is a number. i made it in the recursive way. im just wondering what the different speed would be. is recursive way more efficiently?
boolean isNum(String in){
if(in ==null || in.length() < 1)returnfalse;
int length = in.length();
if(length == 1 && !Character.isDigit(in.charAt(0)))returnfalse;
elseif(length == 2 && (!Character.isDigit(in.charAt(0)) || !Character.isDigit(in.charAt(1))))returnfalse;
elseif(length > 2){
if(!Character.isDigit(in.charAt(0)) || !Character.isDigit(in.charAt(length-1)))returnfalse;
elsereturn isNum(in.substring(1, length-1));
}
returntrue;
}
I'm not an expert, but generally speaking you should avoid recursion if you are looking for optimum performance.
The main reason for this is that none of the (recursive) function call can be terminated until the last function call returns. If you do N recursive calls, N+1 function calls must be stored in memory, which may cause a stack overflow and/or decrease performance (the lingo may be incorrect :) ). Taking this into consideration, non-recursive solutions are much more efficient in most cases, although they may be hard to implement.
So, I would loop through the string and check all characters!
For example (Warning: un-tested code!):
boolean isNumber(String s) {
if (s==null || s.length() < 1) return false;
char[] chars = s.toCharArray();
for (int i=0; i<chars.length; i++) {
if (! Character.isDigit(chars[i]) ) return fase;
}
return true;
Or, you could just use the built-in functions parseXXX:
try { Integer.parseInt(s); } catch(NumberFormatException nfe) { /*error handling*/ }
Of course, you could use Float.parseFloat, Double.parseDouble etc.
Hope this helps!
Regards
Alex>
> I'm not an expert, but generally speaking you should
> avoid recursion if you are looking for optimum
> performance.
I'm not sure if this is always the case, but I'd be willing to bet it's at least correct for linear problems such as the one above. Also note that in the original solution, performance could be greatly increased by intelligent use of a StringBuffer instead of immutable Strings
DaanSa at 2007-7-13 14:17:06 >

> is recursive way more efficiently?
To go off on a bit of a tangent, I'd suggest that you should use recursion to achieve your ends when it is clearer and more concise to do so.
Don't worry too much about the performance aspect of it unless profiling a slow application suggests that it is a bottleneck.
> I'm not an expert, but generally speaking you should
> avoid recursion if you are looking for optimum
> performance.
Not true. This thread explores the problem of finding the height of a tree:
http://forum.java.sun.com/thread.jspa?forumID=426&threadID=565073