Using For Loops Efficiently Android

Using For Loops Efficiently Android

Added by Nasir Mahmood updated on Tuesday, January 2, 2018

Problem:

In this small tutorial we will discuss how to use different kind of For-Loops efficiently.

For Loop:

From The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination;
     increment) {
    statement(s)
}				
				

For-Each Loop:

It is an extension to the classic for loop and it is widly known as "enhanced for" or "for-each".The syntax of this new loop is very simple.

To iterate over the containts of an array

for (type variable: Array){}
				

To iterave over the elements of a colletion

for (type variable: Collection){}				
				

We cannot use it to remove or replace items in a list and iteration over multiple collections in parallel is not possible. We can use it whenever access to only a single element in each iteration is needed. We can use it over both arrays and collections, as well as over any class that implements the interface Iterable.

Performance:

The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface and for arrays. With collections, an iterator is allocated to make interface calls to hasNext() and next(). With an ArrayList, a hand-written counted loop is about 3x faster (with or without JIT), but for other collections the enhanced for loop syntax will be exactly equivalent to explicit iterator usage.

static class Foo {
    int mSplat;
}

Foo[] mArray = ...

public void zero() {
    int sum = 0;
    for (int i = 0; i < mArray.length; ++i) {
        sum += mArray[i].mSplat;
    }
}

public void one() {
    int sum = 0;
    Foo[] localArray = mArray;
    int len = localArray.length;

    for (int i = 0; i < len; ++i) {
        sum += localArray[i].mSplat;
    }
}

public void two() {
    int sum = 0;
    for (Foo a : mArray) {
        sum += a.mSplat;
    }
}				
				

zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.

one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.

two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.

So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected