Idea wish to change StringBuilder to the String
Answered
I have a complex business logic for generating filenames over date. I want to iterate over given dates and load files. I used StringBuilder, but Idea told me that I need to switch to the usual String. Why does it so?
my example code:
String prefix = "some_prefix";
for (LocalDate dateOffset = request.getStartDate();
dateOffset.isBefore(request.getEndDate());
dateOffset = dateOffset.plusDays(1)) {
CharSequence fileName = new StringBuilder()
.append(prefix)
.append(dateOffset.getYear())
.append(File.separator)
.append(dateOffset.getMonthValue())
.append(File.separator)
.append(dateOffset.getDayOfMonth())
.append(File.separator)
.append("lol")
.toString();
}

Please sign in to leave a comment.
Hi, from the inspection's description in "Preferences | Editor | Inspections | Java | Verbose or redundant code constructs | 'StringBuilder' can be replaced with 'String'":
"This inspection only reports when the suggested replacement does not result in significant performance drawback on modern JVMs. In many cases, String concatenation may perform better."
You can suppress inspection or turn it off, see here
Using StringBuilder can only offer better performance if you repeatedly append to it in a loop:
Using a StringBuilder to concatenate a fixed number of items (as is the case in your example) is superfluous.
There's a number of blog posts about this topic, a nice one I found after a quick Google search is this one: https://dzone.com/articles/string-concatenation-performacne-improvement-in-ja