sobota, marca 28, 2009

StringMaker

public class StringMaker {
private ArrayList<string> strings = new ArrayList<string>();

public StringMaker append(Object p) {
strings.add(String.valueOf(p));
return this;
}

public String toString() {
int cnt=0, p=0, l=0;
for (String s : strings) {
cnt +=s.length();
}
char[] value = new char[cnt];
for (String s : strings) {
l = s.length();
s.getChars(0, l, value, p);
p+=l;
}
return new String(value);
}
}

public class Test1 {

private final static String S = "private ArrayList<String> strings = new ArrayList<String>()";

public long[] test1() {
Random r = new Random(System.currentTimeMillis());
StringMaker sm = new StringMaker();
long t1 = System.currentTimeMillis();
for (int i=0; i < 100000; i++) {
sm.append(S.substring(r.nextInt(40)));
}
String result = sm.toString();
long t2 = System.currentTimeMillis();
return new long[] { t2-t1, result.length() };
}

// test2 - to samo na StringBufferze
// test3 - to samo na StringBuilderze
// test4 - to samo na StringBufferze(4000000)
}

BEA JRockit(R) (build R27.6.0-50_o-100423-1.6.0_05-20080626-2104-linux-ia32, compiled mode):
n=100 test1: 50ms, 3950201 chars
n=100 test2: 77ms, 3949690 chars
n=100 test3: 77ms, 3950259 chars
n=100 test4: 41ms, 3950640 chars

Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing):
n=100 test1: 92ms, 3951062 chars
n=100 test2: 118ms, 3949873 chars
n=100 test3: 118ms, 3950118 chars
n=100 test4: 36ms, 3950035 chars

IBM J9 VM (build 2.4, J2RE 1.6.0 IBM J9 2.4 Linux x86-32 jvmxi3260-20090215_29883 (JIT enabled, AOT enabled):
n=100 test1: 64ms, 3949910 chars
n=100 test2: 70ms, 3950291 chars
n=100 test3: 70ms, 3950410 chars
n=100 test4: 31ms, 3949690 chars

0 komentarze: