Java, Assertions and the JIT

I'm trying to reason about how the JIT of Hotspot reasons. I'm mostly interested in the latest compilation stage (C2 compiler). Does the JIT in Java rely on assertions for optimisations? If that was the case, I could imagine that there are examples where code could run faster with assertions enabled.

For example, in a piece of code like this:

static int getSumOfFirstThree(int[] array) {
   assert(array.length >= 3);
   return array[0] + array[1] + array[2];
}
  • Will the JIT, when assertions are enabled, be clever enough to eliminate the bounds checks on the array accesses?
  • Alternatively, are there other cases that you can think of (practical or not) where assertions will actually improve the native code that the JIT will compile?

  • In this case, there is multiple bounds checks to be made, and it is possible the JIT can coalesce them so that only one check is made, however the assertion doesn't avoid the need to make the check.

    Assertions prevent optimisations like inlining as the method is larger and size is a factor in determining whether to inline a method. Typically inlining improves performance but in some cases it doesn't as it can cause the L0 or L1 CPU caches to become inefficient due to larger code being generated.

    An example of where assertion can improve performance is something like this.

    boolean assertionOn = false;
    assert assertionOn = true;
    if (assertionOn) {
       assumeDataIsGood(); // due to checks elsewhere
    } else {
       expensiveCheckThatDataMightNotBeGood();
    }
    

    This is perhaps an anti-pattern to using assertions, but is going to be cheaper with assertions on by intent.

    链接地址: http://www.djcxy.com/p/40264.html

    上一篇: kotlin注释处理器中的可空类型

    下一篇: Java,断言和JIT