2

I recently read this very interesting and highly rated question about Branch prediction, and it got me thinking - how do try-catch clauses affect branch prediction (in java)? There's a lot of information out there regarding if/else, but none seem to focus on this aspect.

Does the branch predictor ever predict that an exception will be thrown? Or is it the equivalent of guessing wrong every time?

Let's put this in context. Suppose we have a List of Strings full of numbers and words. Would the following code be very slow compared to some branch prediction optimised equivalent?

List<String> list = Arrays.asList("1", "some", "3", "words", "12", "in here");

for(String s : list){
  try{
    int number = Integer.parseInt(s);
    // yay - it's a number, do something.
  }catch(Exception e){
    //this is a word - do something else.
  }
}

Or is this roughly equivalent to an if(){}else{} clause in terms of branch prediction?

Sam
  • 1,234
  • 3
  • 17
  • 32
  • ^^ and it may vary by JVM (**will** vary by JVM, since they have different JIT compilers). – T.J. Crowder Nov 19 '19 at 14:20
  • *"Would the following code be very slow compared to some branch prediction optimised equivalent?"* Branch prediction probably isn't the dominant factor there. Exceptions are expensive to throw. But like everything else: If you need to know which of two alternatives will perform better in your specific situation, write both, and do a [proper benchmark of them](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). And that's a fair bit of work, so it's probably better not to bother until/unless you have a specific problem to solve. – T.J. Crowder Nov 19 '19 at 14:22
  • 1
    See https://stackoverflow.com/questions/299068/how-slow-are-java-exceptions which is related – Karol Dowbecki Nov 19 '19 at 14:23
  • Thanks for the comments and resources. I agree that bench-marking this with a specific version of the JVM is probably the best way to go, I'll probably give it a go later. – Sam Nov 19 '19 at 14:45

0 Answers0