java - javac 有多聪明?

标签 java compiler-construction javac

如果我要用 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;}

最佳答案

通常;您应该尽可能编写最简单明了的代码,这样性能会很好。通常,使代码更清晰的性能问题更为重要。在你的例子中,我会这样写。

static final Pattern CODE = Pattern.compile("[A-Z][0-9]{4}");

if (!CODE.matcher(codeInput).matches()) {
    if (verbose) 
        System.out.println("Sorry, I don't understand! Use product codes only.");
    return true;
}

即使这样稍微慢一点,也更清晰,更容易维护恕我直言


javac 几乎没有做任何优化,它们几乎全部由 JIT 在运行时执行。

If I were to compile the following code with javac, would the compiler be clever enough to only evaluate codeInput.length() once,

没有,但是,

or would I potentially get a faster program by putting the evaluations affected by the iterator variable first?

这不像您会注意到差异,因为如果代码运行时间足够长,JIT 就会启动,并且方法将被内联,从而消除对局部变量的需要。

关于java - javac 有多聪明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14119515/

相关文章:

java - 如何从字符串中转义\s(空格字符)?

c++ - <函数> 引用自;找不到符号

Android Java 编译器指令禁用单行代码的警告

javac 代码消除功能

java - Java 8 中的顺序流在调用 collect 时是否使用组合器参数?

java - 我没有得到以下代码 : 的预期输出

java - 如何在 Alpine docker 容器上使用 openjdk 14 启用 ECDHE 密码?

java - 解析 - 为什么 C++ 在模板 var decls 上有问题而 java 在通用 var decls 上却没有?

java - 当使用 lambda 并抛出覆盖异常时,“覆盖方法不会抛出异常”

java - 通过build.gradle文件告诉IntelliJ为Javac设置-parameters标志