1. Overview

In Java, exceptions are generally considered expensive and shouldn’t be used for flow control. This tutorial will prove that this perception is correct and pinpoint what causes the performance issue.

2. Setting Up Environment

Before writing code to evaluate the performance cost, we need to set up a benchmarking environment.

2.1. Java Microbenchmark Harness

Measuring exception overhead isn’t as easy as executing a method in a simple loop and taking note of the total time.

The reason is that a just-in-time compiler can get in the way and optimize the code. Such optimization may make the code perform better than it would actually do in a production environment. In other words, it might yield falsely positive results.

To create a controlled environment that can mitigate JVM optimization, we’ll use Java Microbenchmark Harness, or JMH for short.

The following subsections will walk through setting up a benchmarking environment without going into the details of JMH. For more information about this tool, please check out our Microbenchmarking with Java tutorial.

#java #exception #jvm

Performance Effects of Exceptions in Java
1.15 GEEK