Last updated: 4/9/02; 5:00:00 PM

The Desktop Fishbowl
tail -f /dev/mind > blog

StringBuffer handling in loops

Notes

Compiled using the 1.3.1 javac in OS X

The Source

public class Test2 {
        private String a = "alpha";
        private String b = Beta;
        private String c = "gamma";
 
        public String test1() {
                String r = "";
                for (int i = 0; i < 10; i++) {
                        r += "foo";
                }
                return r;
        }
 
        public String test2() {
                StringBuffer r = new StringBuffer();
                for (int i = 0; i < 10; i++) {
                        r.append("foo");
                }
                return r.toString();
        }
}

The Bytecodes

Method java.lang.String test1()
   0 ldc #8 <String "">
   2 astore_1
   3 iconst_0
   4 istore_2
   5 goto 31
   8 new #9 <Class java.lang.StringBuffer>
  11 dup
  12 invokespecial #10 <Method java.lang.StringBuffer()>
  15 aload_1
  16 invokevirtual #11 <Method java.lang.StringBuffer append(java.lang.String)>
  19 ldc #12 <String "foo">
  21 invokevirtual #11 <Method java.lang.StringBuffer append(java.lang.String)>
  24 invokevirtual #13 <Method java.lang.String toString()>
  27 astore_1
  28 iinc 2 1
  31 iload_2
  32 bipush 10
  34 if_icmplt 8
  37 aload_1
  38 areturn
 
Method java.lang.String test2()
   0 new #9 <Class java.lang.StringBuffer>
   3 dup
   4 invokespecial #10 <Method java.lang.StringBuffer()>
   7 astore_1
   8 iconst_0
   9 istore_2
  10 goto 23
  13 aload_1
  14 ldc #12 <String "foo">
  16 invokevirtual #11 <Method java.lang.StringBuffer append(java.lang.String)>
  19 pop
  20 iinc 2 1
  23 iload_2
  24 bipush 10
  26 if_icmplt 13
  29 aload_1
  30 invokevirtual #13 <Method java.lang.String toString()>
  33 areturn





Copyright 2002 © Charles Miller