如果我要使用javac编译以下代码,那么编译器会足够聪明,仅对一次codeInput.length()进行一次评估,还是通过将受迭代器变量影响的评估放在首位来获得更快的程序?

// edit: The first character must be an upper case letter, the next four must be
// edit: numeric and there must be exactly five characters in total in a product
// edit: code.

for (int i = 1; i < 5; i++)
    if (codeInput.length() != 5 || codeInput.charAt(i) < '0'
        || codeInput.charAt(i) > '9' || codeInput.charAt(0) < 'A'
        || codeInput.charAt(0) > 'Z')
        {if (verbose) System.out.println("Sorry, I don't understand!
            Use product codes only."); return true;}

最佳答案

您的第一个目标应该是代码的简单性和可读性。对于像您提出的问题一样简单的问题,您确实必须竭尽全力将其变成性能瓶颈。正则表达式是最干净,最灵活的字符串验证方法:

boolean valid = codeInput.matches("[A-Z][0-9]{4}");
if (!valid && verbose)
   System.out.println("Sorry, I don't understand! Use product codes only.");
return !valid;


如果您确实希望从中获得最后的性能,则可以预编译正则表达式:

static final Pattern productCodeRegex = Pattern.compile("[A-Z][0-9]{4}");
boolean validate(String codeInput) {
  boolean valid = productCodeRegex.matcher(codeInput).matches();
  ...
}

10-04 13:07