2

I need to have a validation function, boolean isFloat(String) , to check if a given string can be directly converted to an integer. There are at least two approaches on base of Checking If a String is Numeric in Java:

  1. in plain Java:

    isFloat(String f) {
      if (strNum == null) {
        return false;
      }
      try {
        Float.parseFloat(strNum);
      } catch (NumberFormatException nfe) {
        return false;
      }
      return true;
    }
    
  2. in regular expression, hereby I don't list the code

The first approach is more strict forward and easy to understand, whereas one of my colleagues said throwing exception might the whole stack trace, which might affect performance when happening frequently. The second approach might be error-prone as we always need to think about how the expression is formed.

Question: Is the impract of throwing and catching the whole stack trace of an exception really that big?

Rui
  • 3,454
  • 6
  • 37
  • 70
  • 2
    Does this answer your question? [What are the effects of exceptions on performance in Java?](https://stackoverflow.com/questions/299068/what-are-the-effects-of-exceptions-on-performance-in-java) – Amongalen Feb 24 '20 at 13:14
  • A side note, `isFloat` isn't the best name for a method checking if something is an integer ;) – Amongalen Feb 24 '20 at 13:15
  • @Amongalen You meant Double I suppose but I agree. _Edit, I now see that the text says integer so we have 3 types ;)_ – Joakim Danielson Feb 24 '20 at 13:16
  • Why not just measure the difference? –  Feb 24 '20 at 13:17
  • @JoakimDanielson Actually I was reffering to the first sentence, didn't even notice the Double in code. – Amongalen Feb 24 '20 at 13:17
  • I would probably go with the solution shown in this answer: https://stackoverflow.com/a/5439547/4949750 – Amongalen Feb 24 '20 at 13:18

1 Answers1

0

It depends on your performance requirements. Creating an Exception involves creating a stacttrace. This causes measurable more load but as long as there aren't tens or hundrets of those per request (assuming a web application), the effect will be hardly noticeable. If there are hundrets of those exceptions, it mitght be reasonable to find out, where they come from and how to prevent them in forst place (before starting to optimize the code we're seeing here).

Nicktar
  • 5,548
  • 1
  • 28
  • 43