#For Loop Optimizations - Caching values

13 messages · Page 1 of 1 (latest)

lone surge
#

Will

final int length = data_struct.length();

for (int i = 0; i < length; ++i) {}

Perform better than

for (int i = 0; i < data_struct.length(); ++i) {}
```?

Will Java calculate, at each iteration in the second example, the length of the data structure?
daring harborBOT
#

This post has been reserved for your question.

Hey @lone surge! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

lean tusk
#

Java's predefined data structures don't calculate their lengths, they merely return the known value.
So this is merely a matter of calling a method of another class rather than not.

In theory not calling the method more than once is slightly more efficient. In practice you can't tell the difference and various optimizations will make it disappear.

Of course if you make a data structure that does need to compute the length, optimizations are very unlikely to automatically get rid of it.

lone surge
#

All right

#

I see

#

What about some basic basic stuff like ... char[]{}.length? Will it have a difference?

lean tusk
#

I have no idea what that's supposed to be

lone surge
#

char array length

native dirge
lone surge
#

All right

#

This benchmark was done in another community