Markus G.
Markus G.

Reputation: 1718

Performance Difference For-Loop Foreach

I always asked myself "what to use" should I use a for-loop or a foreach. In my opinion it's both the "same". I know for iterating through a list etc. is a foreach better but what if we have the following case :

for (String zipCode : zipCodes) {
    if (zipCode.equals(zip)) {
        return true;
    }
}

or

for (int i = 0; i < zipCodes.length; i++) {
    if (zipCodes[i].equals(zip)) {
        return true;
    }
}

What would be better? Or is in this case really no difference?

Upvotes: 1

Views: 1220

Answers (4)

hagrawal7777
hagrawal7777

Reputation: 14658

First things first - for-each is nothing but syntactic sugar for Iterator. Read this section of JLS. So, I will address this question as a simple FOR loop vs Iterator.

Now, when you use Iterator to traverse over a collection, at bare minimum you will be using two method - next() and hasNext(), and below are their ArrayList implementations:

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = I]; // hagrawal: this is what simple FOR loop does
    }

Now, we all know the basic computing that there will be performance difference if on the processor I have to just execute myArray[i] v/s complete implementation of next() method. So, there has to be a difference in performance.

It is likely that some folk might come back strongly on this, citing performance benchmarks and excerpts from Effective Java, but the only other way I can try to explain is that this is even written in Oracle's official documentation - please read below from RandomAccess interface docs over here.

enter image description here

It is very clearly mentioned that there will be differences. So, if you can convince me that what is written in official docs is wrong and will be changed, I will be ready to accept the argument that there is no performance difference between simple FOR loop and Iterator or for-each.

So IMHO, correct way to put this whole argument is this:

  1. If the collection implements RandomAccess interface then simple FOR loop will perform (at least theoretically) better than Iterator or for-each. (this is what is also written in RandomAccess docs)
  2. If the collection doesn't implement RandomAccess interface then Iterator or for-each will perform (for sure) better than simple FOR loop.
  3. However, for all practical purposes, for-each is the best choice in general.

Upvotes: 3

Rishi
Rishi

Reputation: 1183

Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

Item 46 in Effective Java by Joshua Bloch

Upvotes: 1

Kelevandos
Kelevandos

Reputation: 7082

It is less about optimisation nowadays, as any difference will be unnoticeable, unless you need to process a very large amount of data. Also, if you used a Collection, the performance would depend on the chosen implementation.

What you should really think about is the quality of the code. The rule is that you should use as few elements as possible to present the logic as clearly as possible. The second solution introduces a new element, the i index, which is not actually needed and only makes the code this little bit more complicated. Only use the fori loop if you actually need to know the index in each iteration.

So, from code quality perspective, you should use the first solution :-)

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234635

If zipCodes[i] is not O(1), then the performance of your second case will be much worse. (That said, I don't think there yet exists a container in Java where [] is not O(1)). Put another way, the short form for loop cannot be slower.

Plus the short form for loop is clearer, which really ought to be the primary consideration unless speed matters.

Upvotes: 3

Related Questions