jvm测试用插件--MAT
参照 https://blog.csdn.net/qq_31383041/article/details/73599436
1、intern()方法设计的初衷,就是重用String对象,以节省内存消耗。这么说可能有点抽象,那么就用例子来证明。
- static final int MAX = 100000;
- static final String[] arr = new String[MAX];
- public static void main(String[] args) throws Exception {
- //为长度为10的Integer数组随机赋值
- Integer[] sample = new Integer[10];
- Random random = new Random(1000);
- for (int i = 0; i < sample.length; i++) {
- sample[i] = random.nextInt();
- }
- //记录程序开始时间
- long t = System.currentTimeMillis();
- //使用/不使用intern方法为10万个String赋值,值来自于Integer数组的10个数
- for (int i = 0; i < MAX; i++) {
- arr[i] = new String(String.valueOf(sample[i % sample.length]));
- //arr[i] = new String(String.valueOf(sample[i % sample.length])).intern();
- }
- System.out.println((System.currentTimeMillis() - t) + "ms");
- System.gc();
- }
这个例子也比较简单,就是为了证明使用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) 收藏 举报
浙公网安备 33010602011771号