调优背景:当Java程序存在大量的字符串,而且这些字符串中有很多是重复的。此时可以通过以下方法调优,大大减少程序运行时占用的内存空间。
方法一:将JVM运行参数 -XX:StringTableSize 设大
eg: -XX:StringTableSize=200000
方法二:通过intern方法让字符串入池,减少字符串个数(触发垃圾回收 没入池的字符串被回收掉),节约堆内存的使用
public class Demo1_25 {
public static void main(String[] args) throws IOException {
List<String> address = new ArrayList<>();
System.in.read();
for (int i = 0; i < 10; i++) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("linux.words"), "utf-8"))) {
String line = null;
long start = System.nanoTime();
while (true) {
line = reader.readLine();
if(line == null) {
break;
}
//仅修改这一处代码
address.add(line.intern());
}
System.out.println("cost:" +(System.nanoTime()-start)/1000000);
}
}
System.in.read();
}
}