Closed daniellansun closed 4 years ago
I completed a performance experiment, which is not very strict. The following code costs about 20ms on my local machine.
Without filling stack trace:
package stacktrace;
public class MyException extends RuntimeException {
public MyException(String msg) {
super(msg);
}
public synchronized Throwable fillInStackTrace() {
return this;
}
public static void main(String[] args) {
long b = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
try {
throw new MyException("hello");
} catch (MyException e) {
}
}
long e = System.currentTimeMillis();
System.out.println("## " + (e - b) + "ms");
}
}
The following code costs about 80ms on my local machine.
With filling stack trace:
package stacktrace;
public class MyException extends RuntimeException {
public MyException(String msg) {
super(msg);
}
// public synchronized Throwable fillInStackTrace() {
// return this;
// }
public static void main(String[] args) {
long b = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
try {
throw new MyException("hello");
} catch (MyException e) {
}
}
long e = System.currentTimeMillis();
System.out.println("## " + (e - b) + "ms");
}
}
As you can see, about 75% time can be saved.
I'll submit a PR later :-)
Background
When semantic predicate fails,
FailedPredicateException
will be thrown to change the control flow. But as we all know, filling the stack trace is expensive especially whenFailedPredicateException
is thrown frequently.Proposal
I propose to override
fillInStackTrace()
ofFailedPredicateException
, and its implementation is simplified as follows:its default implementation is:
Advantages & Disadvantages
FailedPredicateException
, but usually we do not care about its stack trace. If we want to addressFailedPredicateException
some day, we can add the state to the exception message, e.g.