StringBuilder and substring performance

与世无争的帅哥 提交于 2019-12-11 12:16:31

问题


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.



来源:https://stackoverflow.com/questions/28755454/stringbuilder-and-substring-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!