概述

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

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐