Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which class to use for this static method, StringBuffer or StringBuilder?

For the following code, which class should I use in a static method, StringBuilder or StringBuffer? Based on the API, StringBuffer is thread-safe, but StringBuilder is not.

public static String getString(int[] arrs) {
    StringBuilder sb = new StringBuilder();  //1
    StringBuffer sb = new StringBuffer();    //2
    for (int i : arrs) {
        sb.append(i);
    }
    return sb.toString();
}
like image 887
user1857098 Avatar asked Jul 30 '26 22:07

user1857098


2 Answers

It's a method-local variable, you won't have concurrent access there... so use StringBuilder

like image 129
Korgen Avatar answered Aug 01 '26 11:08

Korgen


Why worry about thread safety with the code you've shown though? If your StringBuilder isn't being used in a way that requires having to worry about thread safety, then don't spend the overhead required for it needlessly. Use StringBuilder.

like image 37
Hovercraft Full Of Eels Avatar answered Aug 01 '26 11:08

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!