鉴于toString()下面的两个实现,首选哪一个:
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
Run Code Online (Sandbox Code Playgroud)
要么
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
Run Code Online (Sandbox Code Playgroud)
?
更重要的是,鉴于我们只有3个属性,它可能没有什么区别,但你会在什么时候从+concat 切换到 StringBuilder?
当我注意到有关字符串连接的这一点时,我正在查看StringJavadoc:
Java语言为字符串连接运算符(+)提供特殊支持,并为其他对象转换为字符串.
String通过StringBuilder(或StringBuffer)实现连接
从Java 8 JLS 15.8.1开始,它是编译器的选择(强调我的):
实现可以选择在一个步骤中执行转换和连接,以避免创建然后丢弃中间String对象.为了提高重复字符串连接的性能,Java编译器可以使用StringBuffer类或类似技术来减少通过计算表达式创建的中间String对象的数量.
我制作了一个小程序来查看它编写的内容
public class Tester {
public static void main(String[] args) {
System.out.println("hello");
for (int i = 1; i < 5; i++) {
String s = "hi " + i;
System.out.println(s);
}
String t = "me";
for (int i = 1; i < 5; i++) {
t += i;
System.out.println(t);
}
System.out.println(t);
}
}
Run Code Online (Sandbox Code Playgroud)
运行时的输出javap -c Tester显示StringBuilder正在使用的输出:
Compiled …Run Code Online (Sandbox Code Playgroud) String str = "";
try {
BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
while (br.readLine() != null) {
str += br.readLine();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String replace = str.replace("HTTP Request: ", "")
.replace("Resource URL: ","")
.replace("Attribute\t\tDescription", "| Attribute | Type | Description |<P>|----|----|<P>")
.replace("Data Type | Max Length | Requirement |", "")
.replace("N/A", "Object")
.replace("String", "| String")
.replace("255 |", "")
.replace("Required", "**Required**")
.replace("Optional", "**Optional**")
.replace("Request Example <P>", "")
.replace("Response Example <P>", "Nothing"); …Run Code Online (Sandbox Code Playgroud) 我有一个程序在循环中构建一个字符串,我的程序太慢了.现在需要大约600毫秒才能运行Oblig1Test.oppgave7.有什么办法可以加快速度?
Oblig1.toString:
public static String toString(int[] a, char v, char h, String mellomrom)
{
String s ="";
s += v;
if(a.length != 0)
{
for(int i = 0; i < a.length-1; i++)
{
s += a[i] + mellomrom;
}
s += a[a.length-1];
}
s += h;
return s;
}
Run Code Online (Sandbox Code Playgroud)
Oblig1Test:
public static int oppgave7()
{
int[] b = new int[20000];
long tid = System.currentTimeMillis();
Oblig1.toString(b,' ',' '," ");
tid = System.currentTimeMillis() - tid;
if (tid > 40) …Run Code Online (Sandbox Code Playgroud)