Java string concatenation vs string builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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