2

About a performance issue related with String operation in Java:

String s = ".........................,--content I wanted---,....";

Basically I will use for loop to iterate a long String and extract the contents between the ,.

Using substring is to record the begin index and end index during the iteration, and then do a s.subtring(begin,end).

Using StringBuilder, I will append every char between the comma during the iteration.

Is there a performance issue about this? I mean which one will be faster when I have a lot of such operations about extracting the content of a String.

jww
104k107 gold badges454 silver badges975 bronze badges
asked Feb 27, 2015 at 0:28
2
  • 1
    Why wouldn't you just use String#split and the appen the resulting String values? Commented Feb 27, 2015 at 0:51
  • Just curious about the performance. Commented Feb 27, 2015 at 2:00

1 Answer 1

4

string.substring is substantially faster than appending using a StringBuilder.

Pre Java7u6, the substring method returned a new String which kept a reference to the old string value (which is a char array), and adjusted the start and end position. Here is the constructor it called:

 String(int offset, int count, char value[]) {
 this.value = value;
 this.offset = offset;
 this.count = count;
 }

This was changed, and newer versions use the following code:

 Arrays.copyOfRange(value, offset, offset+count);

This is still much faster, since Arrays.copyOfRange uses System.arraycopy, which copies arrays very quickly, and certainly faster than repeated calls to append.

answered Feb 27, 2015 at 0:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.