How to improve java.lang.String performance

Hi,Go to http://raymondtay.blogspot.comto find a way to do this.null
[103 byte] By [tayboonla] at [2007-11-27 8:36:02]
# 1
Post it here thanks, or stay away. Don't troll this site.
ejpa at 2007-7-12 20:32:47 > top of Java-index,Java Essentials,Java Programming...
# 2

It's not my intention to troll the site, I apologize for that.

Recently, i discovered that the String concatenation operator, "+=" was implemented differently in JDK 1.5 (which actually used a StringBuilder class in the class's bytecodes) and i wanted to see how performance compares in the following two code sequences:

public void inefficientStringBuilder() {

String s = "test";

for( int i = 0; i < StringPerformance.NUMBER_OF_RUNS; i++ )

s += Math.random();

}

public void efficientStringBuilder() {

String s = "test";

StringBuilder sb = new StringBuilder(s);

for( int i = 0; i < StringPerformance.NUMBER_OF_RUNS; i++ )

sb.append( Math.random() );

}

I used NetBeans IDE to help in the profiling of the two code sequences and the blog has graphs illustrating the call-tree and heap metrics.

Next, i disassembled the class and discovered that

public void inefficientStringBuilder();

Code:

0: ldc #2;

2: astore_1

3: iconst_0

4: istore_2

5: iload_2

6: ldc #3;

8: if_icmpge 38

11: new #4; < Creation of StringBuilder object

14: dup

15: invokespecial #5; < Invoke StringBuilder's constructor

18: aload_1

19: invokevirtual #6;

22: invokestatic #7;

25: invokevirtual #8;

28: invokevirtual #9;

31: astore_1

32: iinc 2, 1

35: goto 5

38: return

public void efficientStringBuilder();

Code:

0: ldc #2;

2: astore_1

3: new #4; <- Creation of StringBuilder object

6: dup

7: aload_1

8: invokespecial #10; <- Invoke StringBuilder's constructor

11: astore_2

12: iconst_0

13: istore_3

14: iload_3

15: ldc #3;

17: if_icmpge 34

20: aload_2

21: invokestatic #7;

24: invokevirtual #8;

27: pop

28: iinc 3, 1

31: goto 14

34: return

From the disassembled code, it's evident that the old way of using "+=" is no longer valid since there would be many objects created as compared to 1 object created for efficientStringBuilder (I don't know why Sun did it this way) and i knew that its best to use java.lang.StringBuilder directly in the Java Code itself for JDK 1.5 and above.

tayboonla at 2007-7-12 20:32:48 > top of Java-index,Java Essentials,Java Programming...
# 3
This has been known since about 1996 and appears in all the major books about Java. The only difference here is StringBuilder instead of StringBuffer.
ejpa at 2007-7-12 20:32:48 > top of Java-index,Java Essentials,Java Programming...
# 4
I knew about the StringBuffer but i found out about the StringBuilder not long ago, but thanks for the heads up.
tayboonla at 2007-7-12 20:32:48 > top of Java-index,Java Essentials,Java Programming...