安卓优化:NDK函数与Java最终布尔值

huangapple go评论92阅读模式
英文:

Android optimization NDK function vs Java final boolean

问题

以下是您要翻译的内容:

我有一些日志记录代码,只适用于内部构建,我在我的NDK C++中有逻辑来决定这是否是内部构建:

native boolean isInternalBuild();

void log() {
    if (isInternalBuild()) {
        Log.d("LOG", "Log this: " + someLogicToComputeLog());
    }
}

如果我切换到Java的最终布尔值,Java编译器或JIT是否能够优化掉它,或者执行起来是否差不多:

static final boolean INTERNAL_BUILD = false; // 如果这是内部构建,则为true

void log() {
    if (INTERNAL_BUILD) {
        Log.d("LOG", "Log this: " + someLogicToComputeLog());
    }
}
英文:

I have some logging code that should only work for internal builds and I have logic in my NDK C++ to make the decision whether this is an internal build:

native boolean isInternalBuild();

void log() {
    if (isInternalBuild()) {
        Log.d("LOG", "Log this: " + someLogicToComputeLog());
    }
}

Would the Java compiler or JIT be able to optimize it out in case I switch to a Java final boolean or would it perform about the same:

static final boolean INTERNAL_BUILD = false; // or true in case this is an internal build

void log() {
    if (INTERNAL_BUILD) {
        Log.d("LOG", "Log this: " + someLogicToComputeLog());
    }
}

答案1

得分: 3

在第一种情况下,消除测试几乎肯定超出了即时编译器的能力。

在第二种情况下,当表达式是编译时常量表达式且求值为false时,Java编译器很可能(但不保证<sup>1</sup>)会优化掉if语句。这种"条件编译"功能在JLS 14.21中有描述(在该部分的末尾)。

需要注意的是:

  • 该功能仅适用于if语句,
  • 仅在测试满足JLS 15.28中所定义的(编译时)常量表达式时才有效。

由于这种优化通常是由Java字节码编译器执行的,您可以通过使用javap检查字节码来轻松确认您的编译器是否执行了此优化。


<sup>1 - JLS文本内容如下:"优化编译器... 可能选择从生成的类文件中省略该语句的代码..."。它在技术上不是必需的。</sup>

英文:

Optimizing away the test in the first case is almost certainly beyond the capabilities of a JIT compiler.

In the second case, it is likely (but not guaranteed<sup>1</sup>) that the Java compiler will optimize away the if statement when the expression is a compile-time constant expression that evaluates to false. This "conditional compilation" feature is described in JLS 14.21 (at the end of the section).

The caveats are:

  • this feature only works with if statements, and
  • it only works when testing a (compile time) constant expression in the sense of JLS 15.28.

Since this optimization is typically done by the Java bytecode compiler, you can easily confirm that it is being done by your compiler by using javap to examine the bytecodes.


<sup>1 - The JLS text says: "An optimizing compiler ... may choose to omit the code for that statement from the generated class file ...". It is not technically required to do this.</sup>

huangapple
  • 本文由 发表于 2020年6月5日 23:11:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/62218595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定