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];
}
An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Assertions in Java help to detect bugs by testing code we assume to be true. An assertion is made using the assert keyword. Its syntax is: assert condition; Here, condition is a boolean expression that we assume to be true when the program executes.
You should assert for null values whenever you can. It is not a good practice to connect the method call directly with the assert method. One workaround is that you can store the return of that method to a local variable. You can then use that variable to assert for conditions.
Assertions are not enabled by default, because they should be always fullfilled. You enable them to test for that, but then you "know" (as far as you can know) that they are not violated. So you don't need to check the conditions (which might be performance intensive) every time in production code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With