关于=null和clear() 问题(Java性能篇)

白色玫瑰 程序猿

时间: 2023-07-11 阅读: 1 字数:2250

{}
关于=null和clear() 问题(Java性能优化)  以ArrayList为例,根据情况来看吧,ArrayList内部维护的是一个数组。 1. list = null 那么你list = null; 就是释放这个数组对象,当然里面所引用的对象也就释放了。 2. ...

关于=null和clear() 问题(Java性能优化)

<hr>

  以ArrayList为例,根据情况来看吧,ArrayList内部维护的是一个数组。

1. list = null

那么你list = null; 就是释放这个数组对象,当然里面所引用的对象也就释放了。

2. list.clear()

如果list.clear(); 看看源代码就知道了,是把list里面对象遍历赋值为null,意思就是释放list里面所有对象。

  这样就很清楚了,如果你这个list还需要使用,那么你可以使用clear去释放掉list里面所有的数据,GC在回收的时候就有可能回收掉原list里面的这些数据了。如果你都不需要了,那么你就用=null这样GC就有可能把list以及里面关联的一些数据也都回收了。

3. 咱们来看下clear()源码

clear()源码解析: If we take an ArrayList as an example, the clear() method does this:

public void clear() { 
   modCount++;  

   // Let gc do its work 
   for (int i = 0; i < size; i++)  
      elementData[i] = null;  

   size = 0;  
}

  Basically, if elements of a List are not referenced anywhere else in the code there is really no need (or at least you do not gain anything) to call clear(). You also do not need to assign null to the List because it will be garbage collected as soon as it falls out of scope. 译文:   基本上,如果List中的元素没有被引用到代码中的其他地方,那么确实没有必要(或至少你没有获得任何东西)来调用clear()。 您也不需要为List指定null,因为它会在超出范围的情况下被垃圾回收。

原文地址:https://blog.csdn.net/u012406177/article/details/70244920?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168904446616782425164450%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168904446616782425164450&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-17-70244920-null-null.142^v88^insert_down38v5,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96

本文章网址:https://www.sjxi.cn/detil/ee53b78a091648f8b40757ef382cceb0

最新评论

当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号

×

(穷逼博主)在线接单

QQ: 1164453243

邮箱: abcdsjx@126.com

前端项目代做
前后端分离
Python 爬虫脚本
Java 后台开发
各种脚本编写
服务器搭建
个人博客搭建
Web 应用开发
Chrome 插件编写
Bug 修复