Java Enthusiast
Java Enthusiast

Reputation: 1191

Does java perform internal optimization?

Java is an OOP language which has several in-built classes and methods for various purposes. One such example is the String class. The method length(), determines the length of the string. For example,

String str = "hello";
for(int i=0;i<str.length();i++)
{
//code
}

Here, the condition is evaluated if the variable i is less then the length of the string, then the loop iterates. But, does it determine the length every time?

Is the method length(), called every time before the condition is evaluated? If that is the case, then does Java store the variable's value internally in a register for quick access (or) the programmer must do it explicitly like this:

String str = "hello";
int len = str.length();
for(int i=0;i<len;i++)
{
//code
} 

How efficient is this approach?

Upvotes: 1

Views: 79

Answers (2)

Arslan Hashim
Arslan Hashim

Reputation: 51

A modern JIT will probably notice that length() is a simple getter of a final class returning a final primitive value and replace the method call with the int value itself.The optimization penalty is true for C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character.

Upvotes: 2

Vince
Vince

Reputation: 15146

String#length simply refers to a variable. Nothing else. The structure is like this:

class String {
    private int length;

    public int length() {
        return length;
    }
}

Strings are immutable, so theres no reason for it to change in the first place; the only time the length needs to be calculated is when the String is created.

It's common practice to perform the calculations when needed, update a size variable, then refer to a getter for that when you need to get the size. That way you aren't wasting time calculating the size when it hasn't changed. You can see this in ArrayList

As for "under the hood" optimizations, it depends on the VM implementation, as well as the code being executed. Inlining could be performed, as well as some run-time optimizations. But in the end, it depends on the code and the VM.

Upvotes: 0

Related Questions