A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]
. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:
boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.