Use StringBuffer to concatenate strings

Metadata

ID: java-best-practices/use-stringbuffer

Language: Java

Severity: Warning

Category: Performance

Description

Use StringBuffer to create and concatenate long strings. Concatenating strings multiple times slows your program execution.

Non-Compliant Code Examples

class Main {
    public static void main(String[] args) {
        String result = "";
        for (Person p: persons) {
            foo();
            result += p.getName() + ",";
            bar();
        }
        for(int i = 0 ; i < persons.size() ; i++) {
            foo();
            result += persons.get(i).getName() + ",";
            bar();
        }
        return result;
    }
}

Compliant Code Examples

class Main {
    public static void main(String[] args) {
        StringBuilder result = new StringBuilder();
        for (Person p: persons) {
            result.append(p.getName() + ",");
        }
        return result.toString();
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: mervebolat/span-id-preprocessing