Loop through java array efficiently

Question:

Lately I have wanted to start thinking more than solutions, to be effective when programming. And that is why I run into the following question, and as the title says it is:

What is the most efficient way to loop through an array in Java?

And more than importing the method, it is why it is the best way, since this way I can apply this knowledge in other different cases.

Answer:

There is no better way, but there are different ways for your use cases. Since the size of an array does not change in Java after it has been created, the classic way is by iterating over the indices:

// ejemplo de arreglo
Object[] arreglo = new Object[10];
//...
for (int i = 0; i < arreglo.length; i++){
    // aqui se puede referir al objeto con arreglo[i];
}

This method uses a simple loop with a primitive as an index so it is not very expensive, and is used when it is necessary to know the index together with the array object.

Another way if it is not important how many elements exist in the array or a reference to the index is not needed is:

for (Object o : arreglo){
    // en cada iteración "o" se refiere a un objeto del arreglo para todos objetos en el arreglo
}

Both forms require few resources and it must be remembered that it does not make much sense in Java to overthink code optimization, because tremendous intelligence was invested to optimize the execution of the bytecode in the virtual machine from the JIT-compiler (just in time).

You just have to remember that it is advisable in a performance context to avoid very high functions for simple cases if you want to minimize the header. The next example uses more resources, because it involves setting up several extra objects, which always means using more memory and runtime resources:

Iterator i = Arrays.asList(arreglo).iterator();
while(i.hasNext()){
    // trabajar con Objeto o = i.next()
}
Scroll to Top