Proper Use Of String and StringBuffer In Java
// over and over again as I go through code written by people
// who obviously don't understand when to use a String and when
// to use a StringBuffer.
1 2 // I put this block of text wherever I find problems with Strings 3 // and StringBuffers to improve understanding of how each one works 4 // and when to use one or the other. 5 // 6 // Rule #1: Use a StringBuffer if you intend to build a string out of 7 // dynamic elements. That is, if you are going to include the results 8 // of function calls or variables as part of the string then you use 9 // a StringBuffer and do append() calls. StringBuffer's append is 10 // much faster than using "+" to stick together String objects. 11 // 12 // Rule #2: But, if you are just building a string out of static pieces 13 // of text, it's better to use Strings and "+" than creating a 14 // StringBuffer and making append calls. Instead just use a String 15 // and a bunch of "+" signs between the sections. For example: 16 // String test = "this " + "is " + "a " + "test " + "string"; 17 // is _not_ expensive. Why? Because all the pieces are static text and 18 // the compiler can make it into this _as it compiles the code_: 19 // String test = "this is a test string"; 20 // 21 // Rule #3: For goodness sake, do this: 22 // StringBuffer test = new StringBuffer(); 23 // test.append("static string "); 24 // test.append(dynamicCall()); 25 // test.append(" another static string "); 26 // test.append(someVariable); 27 // DON'T DO THIS: 28 // StringBuffer test = new StringBuffer(); 29 // test.append("static string " + dynamicCall()); 30 // test.append(" another static string " + someVariable); 31 // This is officially the worst of all worlds. You need to use a 32 // StringBuffer in this case because you've got some dynamic parts 33 // but there is still addition going on between dynamic parts (the 34 // function call and variable) and static strings. Ack! 35 // 36 // If you can't remember anything else, remember this: 37 // static strings = String and "+" 38 // dynamic strings = StringBuffer and append()