如何加速在Java中进行字符串操作的循环? [英] How to speed up a loop that does string manipulation in Java?

查看:132
本文介绍了如何加速在Java中进行字符串操作的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序在循环中构建一个字符串,而我的程序太慢了。现在运行 Oblig1Test.oppgave7 需要大约600毫秒。有什么办法可以加快速度?

I have a program that builds a string in a loop, and my program is too slow. It takes now about 600 milliseconds to run Oblig1Test.oppgave7. What could be done to speed it up?

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:

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

When the slow operation in your code is the concatenation of many strings, chances are you'll gain a lot by using a 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();
}

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

I was able to pass from 493 ms to 22 ms on my computer.

这篇关于如何加速在Java中进行字符串操作的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆