StringBuilder and substring performance

2019-08-11 15:35发布

问题:

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.

回答1:

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.