Performance - method concatenates strings using + in a loop

I am facing this problem on this line of code, even using .append () inside a 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?

+3


source to share


2 answers


You can create StringBuilder

outside of the loop for

and reuse it.

StringBuilder sb=new StringBuilder();
for (final FieldError fieldError : result.getFieldErrors()) {
      sb.append(fieldError.getField())
           .append(" - ")
           .append(getErrorMessageFromProperties(fieldError.getCode()))
           .append("*");
 } 

      

After adding all to, sb

you can call



 String error=sb.toString()

      

immediately after the cycle for

+7


source


Every time you want to read a database table, you use a loop. As the database tables grow, the number of iterations in the loop grows accordingly. Therefore, you want to avoid any operation in the iterations, which can be costly in terms of performance. In addition, this is one defect that you cannot find during QA or when the application is young, with a test database that has multiple records.



Avoid string concatenation, creating objects in memory, etc. in a loop.

+1


source







All Articles