For loop performance iteration

Question: "We could expect method3 to be faster than method2, why?" but I have no idea. Both methods seem to perform the same number of operations. Can someone please enlighten me?

ArrayList<Person> method2(Person x, ArrayList<Person> people){
    ArrayList<Person> friends = new ArrayList<Person>();
    for (Person y : people) if (x.knows(y)) friends.add(y);
    return friends;  
}


ArrayList<Person> method3(Person x, ArrayList<Person> people){  
    ArrayList<Person> friends = new ArrayList<Person>();  
    for (int=0; i<people.size(); i++){ 
        Person y = people.get(i);
        if (x.knows(y)) friends.add(y);
    }
    return friends;
}

      

+3


source to share


2 answers


This is not true. Both methods will work at the same speed.

To the extent that they won't run at the same speed, two things hold true:



  • It won't make any difference in any practical scenario.

  • You can not say whether he will method2

    or method3

    run faster.

+5


source


"We would expect method3 to be faster than method2, why?"

It may be, but the difference should be minimal and not even considered as information for choosing one or the other.

These two methods of performing the exact same thing with the variance: advanced for

method2()

and classic for

, which refer to List

a get(int index)

for method3()

.

Compiled code method2()

will result in the use of an iterator, which at runtime may be slightly longer to execute, but should not make a significant difference.




For example: An hasNext()

iterator for ArrayList

does some checks and some very minor calculations:

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];
}

      

The A for

that the method uses get(int index)

has less computation:

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

      

+4


source







All Articles