Answer the question
In order to leave comments, you need to log in
How expensive is throw?
It is known that the instruction new Exception()
in Java is quite expensive due to the collection of the stacktrace.
However, sometimes in code that needs to complete in a fixed time, you want to throw an exception StopProcessing (extends RuntimeException)
that will be caught at the top level.
You can avoid the stacktrace overhead by first creating an Exception and storing it in a static final variable, because only the fact of stopping is of interest.
The question is: how much more expensive (and will it be) to do a throw instead of a chain of returns with a check of the stop flags?
Answer the question
In order to leave comments, you need to log in
Of course, the returns will be faster, but are they worth the speed? Exceptions are much nicer and more convenient to work with.
Wrote a little test:
public class Test
{
public static final RuntimeException fex = new RuntimeException();
public static void main(String[] args) throws Exception {
long start;
long end;
start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
testReturn(0);
}
end = System.currentTimeMillis();
System.out.println("Return time: " + (end - start) + "ms");
start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
try {
testExceptionThrow(0);
} catch (RuntimeException e) {
}
}
end = System.currentTimeMillis();
System.out.println("Exception throw time: " + (end - start) + "ms");
start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
try {
testExceptionCreate(0);
} catch (RuntimeException e) {
}
}
end = System.currentTimeMillis();
System.out.println("Exception create time: " + (end - start) + "ms");
}
public static void testReturn(int count) {
if (count > 1000) {
return;
} else {
testReturn(count + 1);
}
}
public static void testExceptionThrow(int count) {
if (count > 1000) {
throw fex;
} else {
testExceptionThrow(count + 1);
}
}
public static void testExceptionCreate(int count) {
if (count > 1000) {
throw new RuntimeException();
} else {
testExceptionCreate(count + 1);
}
}
}
Return time: 15ms
Exception throw time: 203ms
Exception create time: 1079ms
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question