Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance - Method concatenates strings using + in a loop

Tags:

java

sonarqube

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?

like image 333
james Avatar asked Jan 09 '23 17:01

james


2 Answers

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

like image 84
Ruchira Gayan Ranaweera Avatar answered Jan 21 '23 17:01

Ruchira Gayan Ranaweera


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.

like image 32
Qualilogy Avatar answered Jan 21 '23 18:01

Qualilogy