I'm encountering this issue on this line of code even I use .append() inside the loop.
for (final FieldError fieldError : result.getFieldErrors()) {
errors = new StringBuilder(errors).append(fieldError.getField()).append(" - ")
.append(getErrorMessageFromProperties(fieldError.getCode())).append("*").toString();
}
how can I fix this?
You can create StringBuilder
outside the for
loop and reuse it.
StringBuilder sb=new StringBuilder();
for (final FieldError fieldError : result.getFieldErrors()) {
sb.append(fieldError.getField())
.append(" - ")
.append(getErrorMessageFromProperties(fieldError.getCode()))
.append("*");
}
After appending all to sb
you can call
String error=sb.toString()
just after the for
loop
Each time you want to read a database table, you use a loop. As database tables grow along the time, the number of iterations in the loop grow accordingly. So you want to avoid any operation in the iterations that could be costly in terms of performance. Furthermore, this is the kind of defect that you cannot detect during QA or when the application is young, with a test database that has few records.
Avoid string concatenation, creation of objects in memory, etc. in a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With