Java fori和foreach的性能差别

概述

fori和foreach的根本区别在于

  1. fori是通过下标访问
  2. foreach是通过容器的itrator的next()方法来迭代

ArrayList:fori性能高于foreach

因为使用fori,是通过下标访问:

public E get(int index) {
    if (index < 0 || index >= this.size)
      throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
    return (E) ArrayList.this.elementData[offset + index];
}

而使用foreach,是通过iterator的next方法:

 public E next() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    int i = cursor;
    if (i >= limit)
        throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

我们可以看到,对于ArrayList来说,foreach需要做同步检查,所以必然比fori要慢。

LinkedList:fori性能低于foreach

fori,通过下标:

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

//LinkedList是一个双向链表,只需迭代一半
Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

foreach,通过迭代器:

public E next() {
    checkForComodification();
    if (!hasNext())
        throw new NoSuchElementException();

    lastReturned = next;
    next = next.next;
    nextIndex++;
    return lastReturned.item;
}

对于LinkedList,通过下标的话每次都要迭代一半的长度,而通过迭代器,每次迭代只需要移动一下指针。显然foreach性能要高于fori

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值