调用list的clear方法和new一个新的list相比

再一次偶然的机会,看见了list.clear() 方法(ps:很少之前很少看API,只知道常用的,之后要准备看API了),觉得奇怪,便去深入源码研究了一下clear方法的特别之处。

个人之前在循环中要么是每次new一个list集合,要么就是使 list=null,但是在大批量大数据量循环的时候,确实影响性能的开销。

ArrayList 的 clear 方法源码如下:

/**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

我们从中可以发现就是将list集合中的所有对象都释放了,而且集合也都空了,所以我们没必要多次创建list 集合而只需要调用一下 clear() 方法就可以了。

LinkedList 的 clear 方法源码如下:

/**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

从上面我们可以看到,不管是哪个实现类的clear 方式都是将里面的所有元素都释放了并且清空里面的属性 ,这样我们就不用在释放 创建新对象来保存内容而是可以直接将现有的集合制空再次使用。

clear的实现其实也是遍历list内数组将各个元素赋值null,让gc去回收每个元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值