StringBuilder sb = new StringBuilder();
String line = "a very big String";
String trim = line.trim();
String[] split = trim.split("&");
sb.append(split[0]);
sb.append("n");
trim = null;
split = null;
I have three questions:
- In Java 8, trim() and split() will copy the char array. So in the memory, there should be 3 (line, trim and split) copy of the content of line. StringBuilder.append() will also copy the char array. So the
line
,trim
andsplit
will all be collected by gc. Only a copy of split[0] is stored in memory. Is that right? - Will explicitly setting a String field to null (trim = null) accelerate garbage collection and release memory?
- Are there any other operations that can reduce memory usage for this code?
I am facing some full gc and OOM problem. I explicitly setting a String field to null and add System.gc();
, it seems that it works. But I want to know why and is there any other better way?