jvm测试用插件--MAT

参照 https://blog.csdn.net/qq_31383041/article/details/73599436

1、intern()方法设计的初衷,就是重用String对象,以节省内存消耗。这么说可能有点抽象,那么就用例子来证明。

  1. static final int MAX = 100000;  
  2. static final String[] arr = new String[MAX];  
  3.   
  4. public static void main(String[] args) throws Exception {  
  5.     //为长度为10的Integer数组随机赋值  
  6.     Integer[] sample = new Integer[10];  
  7.     Random random = new Random(1000);  
  8.     for (int i = 0; i < sample.length; i++) {  
  9.         sample[i] = random.nextInt();  
  10.     }  
  11.     //记录程序开始时间  
  12.     long t = System.currentTimeMillis();  
  13.     //使用/不使用intern方法为10万个String赋值,值来自于Integer数组的10个数  
  14.         for (int i = 0; i < MAX; i++) {  
  15.             arr[i] = new String(String.valueOf(sample[i % sample.length]));  
  16.             //arr[i] = new String(String.valueOf(sample[i % sample.length])).intern();  
  17.         }  
  18.         System.out.println((System.currentTimeMillis() - t) + "ms");  
  19.         System.gc();  
  20. }  

这个例子也比较简单,就是为了证明使用intern()比不使用intern()消耗的内存更少。

先定义一个长度为10的Integer数组,并随机为其赋值,在通过for循环为长度为10万的String对象依次赋值,这些值都来自于Integer数组。

两种情况分别运行,可通过Window ---> Preferences --> Java --> Installed JREs设置JVM启动参数为-agentlib:hprof=heap=dump,format=b,将程序运行完后的hprof置于工程目录下。再通过MAT插件查看该hprof文件。
两次实验结果如下:

posted on 2019-04-24 15:22  helloJava小白  阅读(82)  评论(0)    收藏  举报

导航