Uzair
Uzair

Reputation: 135

Most efficient usage of substring()

Just curious to know which among the two snippets below is the most efficient?

String outStr = inputStr.substring(20);

(or)

String outStr = inputStr.substring(20, inputStr.length());

Does the first snippet internally invoke a inputStr.length() in case the second argument is not present?

Upvotes: 1

Views: 629

Answers (4)

Jesper
Jesper

Reputation: 206816

If you lookup the source code for class java.lang.String, which you can find in the file src.zip in your JDK installation directory, you'll find these implementations (this is from JDK 6 update 26):

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

public int length() {
    return count;
}

In other words, your first line of code does really do almost exactly the same as your second line of code, there will be no difference in efficiency that will be noticeable in any way.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881423

My advice is to run each of those a gazillion times in a loop and measure how long they take.

If one is noticeably faster, go for that one.

If you find the difference is negligible, optimise for readability (the first one).

Measure, don't guess! That is the number one rule of optimisation.

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89169

The first code, calls String.substring(int beginIndex, int endIndex) internally.

Code:

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

Where count is

The count is the number of characters in the String.

Upvotes: 0

Bozho
Bozho

Reputation: 597096

Not exactly - it invokes substring(beginIndex, count), where count is an internal field holding the number of chars. length() also returns count, however, and so it's +1 method invocation. Virtually the same.

But prefer the one-argument version - it is cleaner to read.

Upvotes: 2

Related Questions