本文介绍了StringBuilder 和子串性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于JavaString操作的一个性能问题:

About a performance issue related with String operation in Java

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

基本上我将使用 for 循环来迭代一个长字符串并提取 , 之间的内容.

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

使用substring就是记录迭代时的开始索引和结束索引,然后做一个s.subtring(begin,end).

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

使用StringBuilder,我将在迭代过程中append逗号之间的每个char.

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.

推荐答案

string.substring 比使用 StringBuilder 附加要快得多.

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

在 Java7u6 之前,substring 方法返回一个新的 String,它保留了对旧字符串值(这是一个字符数组)的引用,并调整了开始和结束位置.这是它调用的构造函数:

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);

这仍然要快得多,因为 Arrays.copyOfRange 使用 System.arraycopy,它可以非常快速地复制数组,而且肯定比重复调用 append.

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

这篇关于StringBuilder 和子串性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:00