Using exceptions for a normal code flow is bad - it’s slow, it’s a poor quality code, and we've all drummed into our heads since day one. At least I have it! This also makes sense, exceptions generate stack traces on every call, stack traces take a long time to generate, and thus the exception is thrown and caught much slower than the equivalent if statement.
So I decided to make a quick example to demonstrate this.
public static void main(String[] args) throws Exception { Object[] objs = new Object[500000]; for (int i = 0; i < objs.length; i++) { if (Math.random() < 0.5) { objs[i] = new Object(); } } long cur = System.currentTimeMillis(); for (Object o : objs) { try { System.out.print(o.getClass()); } catch (Exception e) { System.out.print("null"); } } System.err.println("Try / catch: "+(System.currentTimeMillis() - cur)); cur = System.currentTimeMillis(); for (Object o : objs) { if(o==null) { System.out.print("null"); } else { System.out.print(o.getClass()); } } System.err.println("If: "+(System.currentTimeMillis() - cur)); }
However, when I ran the code, I was shocked to see the following:
Try / catch: 11204 If: 11953
I ran the code again, this time “if” was faster:
Try / catch: 12188 If: 12187
... but only with ms.
All this is done on the server virtual machine, I know that most of the time will be examined by print() statements, and some runs show if the bit is faster than try / catch. But regardless, shouldn't they be close? And how could one generate stack traces faster than a single if statement?
EDIT: To clarify, this question is purely academic - I know well that using exceptions for a normal code flow is bad and will never be so!
source share