xxxxxxxxxx
//new StringBuilder()
using System.Text;
StringBuilder bldr = new StringBuilder();
var startTime = DateTime.Now;
for (int i = 0; i< 1_000_000; i++)
{
bldr.Append(i.ToString());
}
var stopTime = DateTime.Now;
Console.WriteLine($"Started:{startTime} Stopped:{stopTime}");
Console.ReadKey();
//Started:1/13/2023 11:22:10 AM Stopped:1/13/2023 11:22:10 AM
xxxxxxxxxx
// Overuse of String concatenation can build large numbers of String objects
// a huge drain on performance and memory, hence code below is avoided
String firstName = "Chris";
String lastName = "Wells";
String fullName = firstName + " " + lastName;
// StringBuilder
// provides dynamic string manipulation without performance overhead of String class
StringBuilder nameBuffer = new StringBuilder("John");
nameBuffer.append(" ");
nameBuffer.append("Richard");
System.out.println(nameBuffer.toString()); //must convert to Strings before can be printed
xxxxxxxxxx
StringBuilder objects are like String objects, except that they can be modified
xxxxxxxxxx
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello "); //init
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
xxxxxxxxxx
StringBuilder in Java represents a mutable sequence of characters.
Since the String Class in Java creates an immutable sequence of characters,
the StringBuilder class provides an alternative to String Class, as it creates
a mutable sequence of characters
xxxxxxxxxx
public final class StringBuilder
extends Object
implements Serializable, CharSequence