JVM专题(八)-StringTable调优

1.增加桶的个数

因为StringTable(串池)底层是hashmap,实现了去重的功能,所以它的性能跟桶的个数(链表的节点数息息相关),桶数越多,性能越强,所以,当我们数据量较大的时候,适当增加桶的个数,能有效的提高效率。

相关命令

-Xms500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=20000

演示代码

/**
 * 演示串池大小对性能的影响
 * -Xms500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=20000
 */
public class Demo1_24 {

    public static void main(String[] args) throws IOException {
        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;
                }
                line.intern(); //入池操作
            }
            System.out.println("cost:" + (System.nanoTime() - start) / 1000000);
        }
    }
}

由于入池时候会先去查找StringTable中有无这个字符串,hash表的的寻找,桶个数越多越快。
在这里插入图片描述
执行耗时:
在这里插入图片描述
当桶个数为1009时,耗费5141毫秒
在这里插入图片描述

2.考虑是否将字符串对象放入池中,即用intern

相关命令

-Xms500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=20000

演示代码

/**
 * 演示 intern 减少内存占用
 * -XX:StringTableSize=200000 -XX:+PrintStringTableStatistics
 * -Xsx500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=200000
 */
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);
                }
                System.out.println("cost:" +(System.nanoTime()-start)/1000000);
            }
        }
        System.in.read();
    }
}

在这里插入图片描述
内存占用情况:
在这里插入图片描述

入池操作:
在这里插入图片描述

在这里插入图片描述

可以通过intern方法减少重复入池,保证相同的地址在StringTable中只存储一份

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熊猫-IT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值