Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

20
  • 7
    Great answer but I'd just like to add that as far as I know, System.nanoTime() should be used for measuring performance, not System.currentTimeMillis(). Commented May 19, 2013 at 13:15
  • 10
    @SimonAndréForsberg nanoTime() requires Java 1.5 and I had only Java 1.4 available on the system I used for writing the code above. Also it doesn't play a huge role in practice. The only difference between the two is that one is nanosecond the other one milliseconds and that nanoTime is not influenced by clock manipulations (which are irrelevant, unless you or system process modifies the system clock exactly the moment the test code is running). Generally you are right, though, nanoTime is of course the better choice. Commented May 22, 2013 at 14:46
  • 3
    It really should be noted that your test is an extreme case. You show a very small performance hit for code with a try block, but no throw. Your throw test is throwing exceptions 50% of the time it goes through the try. That's clearly a situation where the failure is not exceptional. Cutting that down to only 10% massively cuts the performance hit. The problem with this kind of test is that it encourages people to stop using exceptions altogether. Using exceptions, for exceptional case handling, performs vastly better than what your test shows. Commented Apr 1, 2014 at 0:53
  • 2
    Mecki is right. The question was about comparing relative speed between regular control flow (a return statement) and exceptions. If anything, exceptions should be thrown 100% of the time, and not only 50%. Which means that we could be talking of code 132 times slower! Commented Aug 18, 2014 at 20:31
  • 6
    @Glide A throw is not like a clean return. It leaves a method somewhere in the middle of the body, maybe even in the middle of an operation (that has so far completed only by 50%) and the catch block may be 20 stack frames upwards (a method has a try block, calling method1, which calls method2, which calls mehtod3, ..., and in method20 in the middle of an operation an exception is thrown). The stack must be unwind 20 frames upwards, all unfinished operations must be undone (operations must not be half done) and the CPU registers need to be in a clean state. This all consumes time. Commented Oct 15, 2015 at 23:07