如何加速在Java中进行字符串操作的循环?

mv7*_*700 1 java string

我有一个程序在循环中构建一个字符串,我的程序太慢了.现在需要大约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)
  {
    System.out.println("Oppgave 7: Metoden "
      + "er for ineffektiv. Må forbedres!");
  }
}

public static void main(String[] args) throws IOException
{
   oppgave7();
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 8

当代码中的慢速操作是许多字符串的串联时,使用StringBuilder可能会获得很多收益.

通过将您的toString方法更改为

public static String toString(int[] a, char v, char h, String mellomrom){
    StringBuilder sb = new StringBuilder();
    sb.append(v);
    if(a.length != 0){
        for(int i = 0; i < a.length-1; i++){
                sb.append(a[i]).append(mellomrom); 
        }
        sb.append(a[a.length-1]);
    }
    sb.append(h);
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

我的电脑能够从493毫秒传到22毫秒.