Skip to content

Instantly share code, notes, and snippets.

@nhajratw
Last active December 20, 2015 13:38
Show Gist options
  • Save nhajratw/6139826 to your computer and use it in GitHub Desktop.
Save nhajratw/6139826 to your computer and use it in GitHub Desktop.
Performance of StringBuilder + Write
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
import org.junit.Test;
public class SizeTest {
@Test
public void write_stringbuilder_to_file() throws Exception {
final long startTime = System.currentTimeMillis();
printMemoryInfo();
final StringBuilder builder = new StringBuilder(200 * 10000);
for (int i = 0; i < 10000; i++) {
builder.append("a text line that is about two hundred characters ........................................................................");
}
final long endTime1 = System.currentTimeMillis();
System.out.println("String Builder Creation Time in ms: " + (endTime1 - startTime));
System.out.println("StringBuilder size: " + builder.length());
printMemoryInfo();
final Writer writer = new BufferedWriter(new FileWriter("/tmp/out.txt"));
writer.append(builder.toString());
final long endTime2 = System.currentTimeMillis();
System.out.println("File Writing Time in ms: " + (endTime2 - endTime1));
System.out.println("Total Elapsed Time in ms: " + (endTime2 - startTime));
printMemoryInfo();
}
private void printMemoryInfo() {
final Runtime rt = Runtime.getRuntime();
System.out.println("(MB) Total Memory: " + mb(rt.totalMemory()) + " Free Memory: " + mb(rt.freeMemory()) + " Max Memory: " + mb(rt.maxMemory()));
}
private long mb(final long memory) {
return memory / 1024 / 1024;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment