Skip to content

Instantly share code, notes, and snippets.

@claraj
Last active March 9, 2017 21:25
Show Gist options
  • Save claraj/2ebeab5f2ac5a269a12cdac8aeef240d to your computer and use it in GitHub Desktop.
Save claraj/2ebeab5f2ac5a269a12cdac8aeef240d to your computer and use it in GitHub Desktop.
package com.company;
/**
* Created by admin on 3/9/17.
*/
public class Stringbuilder2 {
public static void main(String[] args) {
int length = 100000;
int c = 0;
// 100,000 character length String generated with StringBuilder
long tstart = System.currentTimeMillis();
StringBuilder builder = new StringBuilder();
while (c++ < length ){
builder.append('-');
}
String line = builder.toString();
long tdelta = System.currentTimeMillis() - tstart;
System.out.println("Building a very long String with StringBuilder " + tdelta);
// 6 - 7 milliseconds for StringBuilder
// Same length string, by concatenating "-" onto an existing String
tstart = System.currentTimeMillis();
String line2 = "";
c = 0;
while (c++ < length ){
line2 += "-";
}
tdelta = System.currentTimeMillis() - tstart;
System.out.println("Building a very long String with by concatenating Strings " + tdelta);
// 2.5 - 3 seconds for String concatenation
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment