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);
}
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:Where
countis the value returned byString.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.