Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java string concatenation vs string builder
package tostring;
public class Main {
public static void main(String[] args) {
int n = 1000, iterations = 10000;
long len, t0, t1;
// string builder: < 1 second
len = 0;
t0 = System.currentTimeMillis();
for (int j = 0; j < iterations; j++) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; i++) {
builder.append(i);
}
len += builder.toString().length();
}
t1 = System.currentTimeMillis();
System.out.println(len + " " + (t1 - t0));
// string concatenation: 10 seconds
len = 0;
t0 = System.currentTimeMillis();
for (int j = 0; j < iterations; j++) {
String res = "";
for (int i = 0; i < n; i++) {
res += i;
}
len += res.length();
}
t1 = System.currentTimeMillis();
System.out.println(len + " " + (t1 - t0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.