检查String是否仅包含字母数字字符的最快方法是什么.
我有一些代码会嚼掉很多CPU,我想知道是否会比使用预编译的正则表达式更快.
更新:这么多的投票,关心解释?Stackoverflow不应该用于讨论用于实现任务的算法可能更快?
aro*_*oth 33
使用String.matches(),如:
String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));
这可能不是绝对"最快"的可行方法.但总的来说,试图与那些在性能方面编写语言"标准库"的人竞争并没有什么意义.
Jac*_*cob 24
我已经编写了验证"正确"答案的测试.在运行Java 1.6的四核OSX10.8机器上完成测试
有趣的是,使用正则表达式比手动迭代字符串慢大约5-10倍.此外,isAlphanumeric2()功能略快于isAlphanumeric().
public class QuickTest extends TestCase {
    private final int reps = 1000000;
    public void testRegexp() {
        for(int i = 0; i < reps; i++)
            ("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
    }
public void testIsAlphanumeric() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric2("ab4r3rgf"+i);
}
    public boolean isAlphanumeric(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isDigit(c) && !Character.isLetter(c))
                return false;
        }
        return true;
    }
    public boolean isAlphanumeric2(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;
    }
}