The difference between String and StringBuilder

The main difference between String and StringBuilder is that strings are immutable. They are immutable. Operations on strings do not affect them unless they assign the changed value to String. While String operations generate a lot of intermediate values that consume memory, StringBuffer operations operate directly on the original object, such as:

	// Concatenate String
	// Create a new String and push it onto the stack to point to "hello" in the constant pool
	String str = new String("hello");
	System.out.println(str);//hello
	// We can concatenate strings only by reassigning them
	// New String("hello,word") in the heap; And point STR to the newly created location
	str = str+",world";
    System.out.println(str);//hello,word
	
	
	// String concatenation to StringBuilder
	// Create a StringBuilder object
	StringBuilder strb = new StringBuilder("hello");
	System.out.println(strb);//hello
	To concatenate StringBuilder, we simply call the StringBuilder append method
	New StringBuilder("hello"); The statement becomes new StringBuilder(" Hello,word");
	strb.append(",word");
	System.out.println(strb);//hello,word
Copy the code

The difference between StringBuilder and StringBuffer

Since StringBuilder and StringBuffer are basically the same, the difference between String and StringBuilder is also the difference between String and StringBuffer.

The difference between StringBuilder and StringBuffer is that StringBuffer is thread-safe and StringBuilder is not, so StringBuilder is more efficient than StringBuffer, There are few thread-safety concerns about strings in everyday development, so StringBuilders are often used.

Execution efficiency:

The StringBuilder > StringBuffer > String