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();
}
It's a method-local variable, you won't have concurrent access there... so use StringBuilder
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With