【发布时间】:2016-08-29 02:29:21
【问题描述】:
我有一个在循环中构建字符串的程序,但我的程序太慢了。现在运行Oblig1Test.oppgave7 大约需要 600 毫秒。可以做些什么来加快速度?
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;
}
Oblig1Test:
public static int oppgave7()
{
int[] b = new int[20000];
long tid = System.currentTimeMillis();
Oblig1.toString(b,' ',' '," ");
tid = System.currentTimeMillis() - tid;
if (tid > 40)
{
System.out.println("Oppgave 7: Metoden "
+ "er for ineffektiv. Må forbedres!");
}
}
public static void main(String[] args) throws IOException
{
oppgave7();
}
【问题讨论】:
-
使用 StringBuilder 构建你的字符串
-
我在这里并没有真正得到反对意见:OP 有一个精确的问题,并制造了复制所需的一切。
-
这个问题似乎是题外话,因为它属于Code Review。