Katy Fang
Katy Fang

Reputation: 21

Recalculating condition in for loop or not

Say I have (Java)

String word = args[0];
for (int i = 0; i < word.length(); i++) {}

I know the .length() method on a string isn't necessarily costly, but just to confirm: would this recalculate word.length() on each pass of the for loop? Would it be better to define

int length = word.length;

and use i < length as the condition in the loop?

Upvotes: 2

Views: 233

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31851

The length of the String is NOT calculated each time you call word.length(). That's because the String class stores the length as a field upon the creation.

If you see the code for length() method of java.lang.String class, it only contains this:

public int length() {
    return value.length;
}

And so doing

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

Will have the same performance when done like this:

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

 
 

Also note that the former code moves the call outside the loop which basically removes the need for the method call. However, that would be a trivial performance enhancement.

Upvotes: 3

David Ehrmann
David Ehrmann

Reputation: 7576

Java strings are constant, and the length() method is implemented to be fast (unlike strlen in c). That code will be fine.

That said, one way to avoid this fear is counting to zero. It's marginally faster because you only make a single method call and comparisons to 0 are cheaper than non-zero. Marginally cheaper.

for (int i = word.length() - 1; i >= 0; --i) ...

Another is using a CharacterIterator, but it's overkill for this:

 CharacterIterator iter = new StringCharacterIterator(word);
 for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) ...

Upvotes: 2

Related Questions