5 ms·
The code: public int parseOrDefault(String value, int defaultValue) { if (value == null || value.isBlank()) return defaultValue; for (int i = 0;
by Okx 6mo ago
The code:
public int parseOrDefault(String value, int defaultValue) {
if (value == null || value.isBlank()) return defaultValue;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (i == 0 && c == '-') continue;
if (!Character.isDigit(c)) return defaultValue;
}
return Integer.parseInt(value);
}
Is probably worse than Integer.parseInt alone, since it can still throw NumberFormatExceptions for values that overflow (which is no longer handled!). Would maybe fix that. Unfortunately this is a major flaw in the Java standard library; parsing numbers shouldn't throw expensive exceptions.
- deepsun 6mo agoAnd it will fail with "-"
- j-vogel 6mo agoGood catches from several of you. The original fix dropped the try-catch entirely which was a regression for overflow and edge cases like a bare "-". Updated the post to keep a try-catch around the final parseInt as a safety net. The pre-validation still avoids the expensive path for the common cases, which is the core point. Appreciate the feedback.
- zahlman 6mo agoNot to mention it's extra work in the case where the input usually is valid.