StringBuilder memory consumption
807589Sep 28 2008 — edited Sep 28 2008Hi,
I am using StringBuilder to build a long string and I had noticed in windows task manager that the javaw process takes a lot more memory than I had expected.
For example, writting the following class:
public class testStringBuilder {
static String TEXT = "1000000";
private static StringBuilder str = new StringBuilder(60000000);
public static void main(String[] args) {
for (int i = 1000000; i < 9000000; i++) {
String tmp = Integer.toString(i);
str.append(tmp);
}
str.trimToSize();
}
}
If I define the StringBulder with initial size 60,000,000 which is bigger than what I need (56,000,000) it takes with the above example ~243MB, if I remove the str.trimToSize it takes ~133MB.
If not using tmp and using the "TEXT" it takes ~236MB and without the trimToSize it takes 125MB.
First I don't understand where is the 8MB wasted, calling the GC didn't help.
Doing the same test but without given the 60,000,000 in the constructor it takes:
1. with the String tmp ~286MB and without the trimToSize ~250MB.
2. without the String tmp using the "TEXT" it takes ~266MB and without the trimToSize ~231MB.
My question is what is the best way to build strings and how to make it not wasting so much memory?
Thanks,
Tal