Tux
Tux

Reputation: 1916

In Java, is substring(int k, int y) or substring(int k) more efficient performance wise?

For example, lets say I had the following code:

String s1 = "foobar";
s1 = s1.substring(3);

Would that code be less efficient than:

String s1 = "foobar";
s1 = s1.substring(3, 6);

I was thinking that the two parameter method would be more efficient performance wise because the single parameter method uses a loop to loop through the index until the length is reached. This means that the JVM has to call the length() method to find out when to stop looping.

But the two parameter method only loops through until the last index number is reached.

Can anyone confirm or deny my hypothesis?

EDIT: I don't really understand this code in the source (last return statement) but here is the java String class source:

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
     }
     if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
     }
    if (beginIndex > endIndex) {
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :    // I don't understand this part
         new String(offset + beginIndex, endIndex - beginIndex, value);
}

Upvotes: 1

Views: 908

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

String.substring() is constant time1, it simply provides smaller view on the original string. Moreover the version with one parameter just... delegates to the one with two:

public String substring(int beginIndex) {
    return substring(beginIndex, count);
}

Where count is the value returned by String.length(). It doesn't really matter which version you choose, they are both blazingly fast.

1 - apparently no longer true as of Java 7 update 6. But it's irrelevant to your question.

Upvotes: 10

bhuang3
bhuang3

Reputation: 3633

In java source code, substring(beginIndex) will invodke substring(beginIndex, count)

Upvotes: 0

AlexWien
AlexWien

Reputation: 28737

 public String substring(int beginIndex, int endIndex) 

is slightly faster because

 public String substring(int beginIndex) {
      return substring(beginIndex, count);
 }

so you would avoid one indirection. But its is not worth to think about that.

Upvotes: 1

Steve
Steve

Reputation: 71

I don't think there is any difference. If you see the String class source code substring(int beginIndex) -- simply calls the substring(beginIndex, lengthOfTheString)

Upvotes: 1

Related Questions