Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of method call in for loop condition

I am writing a game engine, in which a set of objects held in a ArrayList are iterated over using a for loop. Obviously, efficiency is rather important, and so I was wondering about the efficiency of the loop.

for (String extension : assetLoader.getSupportedExtensions()) {
    // do stuff with the extension here
}

Where getSupportedExtension() returns an ArrayList of Strings. What I'm wondering is if the method is called every time the loop iterates over a new extension. If so, would it be more efficient to do something like:

ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();

for (String extension : supportedExtensions) {
    // stuff
}

? Thanks in advance.

like image 328
Isaac Woods Avatar asked Mar 30 '15 10:03

Isaac Woods


People also ask

Are method calls allowed in a condition in a while loop?

Yes, you can use any expression which evaluates to a Boolean value.

Can we call method in for loop in Java?

In the main method, you can't use a for loop because you don't know in advance how many times the user wants to input. The while loop, on the other hand, checks that the input is not -1 and then prints out the grade for each iteration. You might need to see a tutorial about for loops though.

Why for loop is efficient?

In a for loop, the index of iteration is always a clearly defined variable. By common practice, the variable is usually the letter i. This makes it easy to index one or more arrays by the index. For loops can easily be used to iterate through elements of multidimensional arrays using nested for loops.

Can we call a method in for loop?

We can call a function from inside of for loop.


1 Answers

By specification, the idiom

for (String extension : assetLoader.getSupportedExtensions()) {
  ...
}

expands into

for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();)
{
    String extension = it.next();
    ...
}

Therefore the call you ask about occurs only once, at loop init time. It is the iterator object whose methods are being called repeatedly.

However, if you are honestly interested about the performance of your application, then you should make sure you're focusing on the big wins and not small potatoes like this. It is almost impossible to make a getter call stand out as a bottleneck in any piece of code. This goes double for applications running on HotSpot, which will inline that getter call and turn it into a direct field access.

like image 192
Marko Topolnik Avatar answered Nov 09 '22 18:11

Marko Topolnik