Java 性能优化
Java 性能优化
Java 性能优化的方向:提高响应速度、减少内存占用
Java性能监控工具
JDK自带性能分析工具
性能分析工具
提高响应速度
使用多线程
增加服务器
缓存CDN
减少内存占用
使用IntObjectHashMap 替换Map<Integer,Object>
首先引入依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.75.Final</version>
</dependency>
<!--openjdk jol-core-->
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-cli</artifactId>
<version>0.16</version>
</dependency>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.16</version>
</dependency>
直接上测试代码
首先使用常用的Map<Integer,String>
public class IntObjectHashMapTest {
private static final Logger LOGGER = LoggerFactory.getLogger(IntObjectHashMapTest.class);
public static void main(String[] args) throws InterruptedException {
long freeMemory = Runtime.getRuntime().freeMemory();
LOGGER.info("before freeMemory {} k Byte", freeMemory);
int maxSize = 1000;
HashMap<Integer,String> hashMap = new HashMap<>();
for (int i = 0; i < maxSize; i++) {
hashMap.put(i, String.valueOf(i));
}
//查看内存占用总大小
LOGGER.info("hashMap size:[{}] Byte", GraphLayout.parseInstance(hashMap).totalSize());
freeMemory = Runtime.getRuntime().freeMemory();
LOGGER.info("after freeMemory {} k Byte", freeMemory);
TimeUnit.HOURS.sleep(1L);
}
}
使用 Netty 的 IntObjectHashMap
public class IntObjectHashMapTest {
private static final Logger LOGGER = LoggerFactory.getLogger(IntObjectHashMapTest.class);
public static void main(String[] args) throws InterruptedException {
long freeMemory = Runtime.getRuntime().freeMemory();
LOGGER.info("before freeMemory {} k Byte", freeMemory);
int maxSize = 1000;
IntObjectHashMap<String> hashMap = new IntObjectHashMap<>();
for (int i = 0; i < maxSize; i++) {
hashMap.put(i, String.valueOf(i));
}
//查看内存占用总大小
LOGGER.info("hashMap size:[{}] Byte", GraphLayout.parseInstance(hashMap).totalSize());
freeMemory = Runtime.getRuntime().freeMemory();
LOGGER.info("after freeMemory {} k Byte", freeMemory);
TimeUnit.HOURS.sleep(1L);
}
}
运行上面的代码,通过日志输出,我们可以看出来IntObjectHashMap更加节省内存
结论: 可以使用IntObjectHashMap替换Map<Integer,Object>,因为IntObjectHashMap的key是int类型,而Map<Integer,Object>的key是Integer类型,是对象类型
int类型占4个字节,对象类型占用字节比基本类型int大,有兴趣可以搜索 一个对象占用几个字节
参考链接
https://docs.oracle.com/javase/7/docs/technotes/tools/index.html#troubleshoot
未完待续...
作者:努力为明天
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!