What are the effects of exceptions on performance in Java?

前端 未结 17 2386
情深已故
情深已故 2020-11-22 01:21

Question: Is exception handling in Java actually slow?

Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn\'t be used for n

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:34

    Just compare let's say Integer.parseInt to the following method, which just returns a default value in the case of unparseable data instead of throwing an Exception:

      public static int parseUnsignedInt(String s, int defaultValue) {
        final int strLength = s.length();
        if (strLength == 0)
          return defaultValue;
        int value = 0;
        for (int i=strLength-1; i>=0; i--) {
          int c = s.charAt(i);
          if (c > 47 && c < 58) {
            c -= 48;
            for (int j=strLength-i; j!=1; j--)
              c *= 10;
            value += c;
          } else {
            return defaultValue;
          }
        }
        return value < 0 ? /* übergebener wert > Integer.MAX_VALUE? */ defaultValue : value;
      }
    

    As long as you apply both methods to "valid" data, they both will work at approximately the same rate (even although Integer.parseInt manages to handle more complex data). But as soon as you try to parse invalid data (e.g. to parse "abc" 1.000.000 times), the difference in performance should be essential.

提交回复
热议问题