My name is Vasyl Khrystiuk‎ > ‎process‎ > ‎main‎ > ‎

String n StringBuilder perfomance


Source:

public class StringTest {

  private int begincount;
  private int endcount;
  
  public static void main(String[] args) {
    StringTest test1 = new StringTest(10000,20000);
    test1.concat();
    test1.append();

    StringTest test2 = new StringTest(20000,30000);
    test2.append();
    test2.concat();
  }

  public StringTest(int begincount,int endcount) {
    this.begincount = Math.min(begincount, endcount);
    this.endcount = Math.max(begincount, endcount);
  }

  private void concat() {
    String foo = "";
    String appendthis = null;
    long start = System.currentTimeMillis();
    for (int i = begincount; i < endcount; i++) {
      appendthis = Integer.toString(i); 
      foo += appendthis;
    }
    System.out.println("String concat took "
        + (System.currentTimeMillis() - start) + " ms");
  }

  private void append() {
    StringBuilder sb = new StringBuilder();
    String appendthis = null;
    long start = System.currentTimeMillis();
    for (int i = begincount; i < endcount; i++) {
      appendthis = Integer.toString(i);
      sb.append(appendthis);
    }
    System.out.println("String append took "
        + (System.currentTimeMillis() - start) + " ms");
  }

}


* This source code was highlighted with Source Code Highlighter.


Results:
String concat took 1219 ms
String append took 0 ms
String append took 15 ms
String concat took 1203 ms


Decompiled code:
import java.io.PrintStream;

public class StringTest{

  private int begincount;
  private int endcount;

  public static void main(String args[])  {
    StringTest test1 = new StringTest(10000, 20000);
    test1.concat();
    test1.append();
    StringTest test2 = new StringTest(20000, 30000);
    test2.append();
    test2.concat();
  }

  public StringTest(int begincount, int endcount)  {
    this.begincount = Math.min(begincount, endcount);
    this.endcount = Math.max(begincount, endcount);
  }

  private void concat()  {
    String foo = "";
    String appendthis = null;
    long start = System.currentTimeMillis();
    for(int i = begincount; i < endcount; i++)    {
      appendthis = Integer.toString(i);
      foo = (new StringBuilder(String.valueOf(foo))).append(appendthis).toString();
// !!!!!!!!!!!!!
    }

    System.out.println((new StringBuilder("String concat took ")).append(System.currentTimeMillis() - start).append(" ms").toString());
  }

  private void append()  {
    StringBuilder sb = new StringBuilder();
    String appendthis = null;
    long start = System.currentTimeMillis();
    for(int i = begincount; i < endcount; i++)    {
      appendthis = Integer.toString(i);
      sb.append(appendthis);// !!!!!!!!!!!!!
    }

    System.out.println((new StringBuilder("String append took ")).append(System.currentTimeMillis() - start).append(" ms").toString());
  }
}

* This source code was highlighted with Source Code Highlighter.








Comments