开发者

Most efficient usage of substring()

开发者 https://www.devze.com 2023-04-12 09:54 出处:网络
Just curious to kn开发者_Go百科ow which among the two snippets below is the most efficient? String outStr = inputStr.substring(20);

Just curious to kn开发者_Go百科ow 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?


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号