How to speed up a loop that does string manipulation in Java? -


i have program builds string in loop, , program slow. takes 600 milliseconds run oblig1test.oppgave7. done speed 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 = 0; < 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 ineffektiv. må forbedres!");   } }  public static void main(string[] args) throws ioexception {    oppgave7(); } 

when slow operation in code concatenation of many strings, chances you'll gain lot using stringbuilder.

by changing tostring method to

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 = 0; < a.length-1; i++){                 sb.append(a[i]).append(mellomrom);          }         sb.append(a[a.length-1]);     }     sb.append(h);     return sb.tostring(); } 

i able pass 493 ms 22 ms on computer.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -