Search code examples
arraysperformanceloopsforeachlibgdx

Which loop syntax is the fastest for Array Datatype in Libgdx?


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

Quoting https://developer.android.com/training/articles/perf-tips.html#Loops it's recommend to use 'for each loop syntax' to achieve better performance. But on the other hand the article says that it does not make any difference for devices with JIT to use zero() or two() whereas zero() is the slowest.

Ive also found articles where it's not recommend to use two() but one() because a for each loop may create garbage.

I want to know what is the best to iterate through all elements of an Array Datatype from LibGDX.

Here are some articles: https://github.com/libgdx/libgdx/wiki/Collections https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Array.html

I'm still confused


Solution

  • two() is better option in my opinion.

    Array of Libgdx is optimized to avoid garbage collection as much as possible. They do this in many ways.

    1. One way is the one you already pointed out, by trying to avoid memory copies when possible.

    2. re-using of iterators.

    3. Use IntArray, that Avoids the boxing that occurs with ArrayList.