Much has been written about the benefits of using StringBuilder over string concatenation. So much so that there seems to be overuse of StringBuilder class, causing performance issues again.
If you're using StringBuilder and string concatenation a lot in your program, here are a few more things to ponder:
Examples:
Bad
String.Format("{0}.{1}", DeclaringType.FullName, Name)
Better
DeclaringType.FullName + "." + Name
Bad:
StringBuilder sb = new StringBuilder(); bool first = true; if (GetFlag((int) PolicyStatementAttribute.Exclusive )) { sb.Append( "Exclusive" ); first = false; } if (GetFlag((int) PolicyStatementAttribute.LevelFinal )) { if (!first) sb.Append( " " ); sb.Append( "LevelFinal" ); } return sb.ToString();
This version is more costly for several reasons:
Better: if you use string + operator, there will be no StringBuilder object, no extra copy, no new buffer allocation, and best of all no new string is generated if it's just a single word.
String p1 = null; String p2 = null; String p3 = null; if (GetFlag((int) PolicyStatementAttribute.Exclusive)) { p1 = "Exclusive"; } if (GetFlag((int) PolicyStatementAttribute.LevelFinal)) { if (p1 != null) { p2 = " "; } p3 = "LevelFinal"; } return p1 + p2 + p3;