Suma
Suma

Reputation: 34403

Why is debugging with some exceptions enabled much slower?

Consider following code:

public class JMain {
    private final static int forLength = 6;

    private static void returnFromFor(int breakAt) {
        try {
            for (int j = 0; j < forLength; j++) {
                if (j == breakAt) {
                    throw new Throwable("break");
                }
            }
        } catch (Throwable ignored) {
        }
    }

    public static void main(String args[]) {
        long start = System.currentTimeMillis();
        int iterations = 100000;
        for (int i = 0; i < iterations; i++) {
            returnFromFor(i % forLength);
        }

        long end = System.currentTimeMillis();
        System.out.println(((Long) (end - start)).toString() + " ms");
    }
}

When I run this code in IntelliJ IDEA debugger with exception breakpoint enabled for java.lang.IllegalArgumentException, it runs very slow, about 1800 ms on my computer. When I run it with no exceptions breakpoints, or with breakpoint enabled for java.lang.UnsupportedOperationException, it is about 10x faster.

My questions are:

The system I am running this on is:

Note: the code above is demonstrating the issue I have with a complex Scala. If anyone is interested in the more natural Scala code demonstration, here it comes:

object Main extends App {

  val forLength = 6
  def returnFromFor(breakAt: Int): Unit = {
    for (j <- 0 until forLength) {
      if (j == breakAt) return
    }
  }

  val start = System.currentTimeMillis()
  val iterations = 100000
  for (i <- 0 until iterations) {
    returnFromFor(i%forLength)
  }
  val end = System.currentTimeMillis()
  println(s"Duration ${end-start} ms")

}

Upvotes: 2

Views: 200

Answers (1)

apangin
apangin

Reputation: 98294

IDEA does not set exception breakpoint until the target exception class is loaded.

UnsupportedOperationException is never loaded during a lifecycle of your program. That's why the program runs as fast as without breakpoints at all.

IllegalArgumentException is much more popular class, it is loaded somewhere inside JDK class library during JVM startup. In this case the exception breakpoint is indeed set, so that the debugger receives notifications about all exceptions thrown in your program.

Upvotes: 4

Related Questions