Lately I have wanted to start thinking more than about solutions, about being efficient when programming. And that is why I come across the following doubt, and as the title says it is:
What is the most efficient way to iterate through an array in Java?
And more than importing the method, it is why it is the best way, since that way I can apply this knowledge in other different cases.
There is no best 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:
This method uses a simple loop with a primitive as the index so it's not too expensive, and is used when you need to know the index along with the array object.
Another way if it doesn't matter how many elements exist in the array or no reference to the index is needed is:
Both ways need few resources and you have to remember that it doesn't make much sense in Java to overthink code optimization, because a tremendous amount of intelligence was invested in optimizing the execution of the bytecode in the virtual machine from the JIT-compiler (just in time).
Just remember that it is recommended 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 installing several extra objects, which always means more runtime and memory use:
Since java 8 you can use functional programming with Lambdas expressions
Try to make the code as readable as possible.
I hope it serves you Greetings.
If you mean to traverse an array completely (which would be reading all its elements) I really don't think any optimization can be applied (or be negligible) beyond readability one way or another, this is because the compiler will end up doing the conversion of it.
I leave you this question in the English version, with more complete answers in case it can help you: https://stackoverflow.com/questions/1006395/fastest-way-to-iterate-an-array-in-java-loop-variable -vs-enhanced-for-statement
//We declare the variable int []array=new int[100];