Initiative: To observe the cost of String immutability versus the efficiency of StringBuilder and StringBuffer.
public class StringPerformance { // Define class to benchmark string manipulation efficiency
public static void main(String[] args) { // Entry point for the performance benchmark
int iterations = 20000; // Define number of times to perform string concatenation
System.out.println("--- String Benchmarking (" + iterations + " loops) ---"); // Print header
// 1. Immutable String Test
long start = System.currentTimeMillis(); // Record start time in milliseconds
String s = ""; // Initialize an empty immutable string
for (int i = 0; i < iterations; i++) { // Loop twenty thousand times
s += "a"; // Append 'a' using concatenation (creates new object every time)
} // End of the slow loop
long end = System.currentTimeMillis(); // Record the end time
System.out.println("String (Immutable) time: " + (end - start) + "ms"); // Print total duration
// 2. Mutable StringBuilder Test (Single-threaded optimized)
start = System.currentTimeMillis(); // Reset the start timer
StringBuilder sb = new StringBuilder(); // Initialize a mutable string builder object
for (int i = 0; i < iterations; i++) { // Loop twenty thousand times
sb.append("a"); // Append 'a' directly to existing memory buffer
} // End of the fast loop
end = System.currentTimeMillis(); // Record the end time
System.out.println("StringBuilder (Mutable) time: " + (end - start) + "ms"); // Print total duration
// 3. Mutable StringBuffer Test (Thread-safe)
start = System.currentTimeMillis(); // Reset the start timer
StringBuffer sbuf = new StringBuffer(); // Initialize a thread-safe mutable buffer
for (int i = 0; i < iterations; i++) { // Loop twenty thousand times
sbuf.append("a"); // Append 'a' directly to synchronized buffer
} // End of the thread-safe loop
end = System.currentTimeMillis(); // Record the end time
System.out.println("StringBuffer (Thread-safe) time: " + (end - start) + "ms"); // Print total duration
System.out.println("\nConclusion: Immutable Strings are significantly slower in loops."); // Log result
System.out.println("Benchmarking Complete."); // Final log for program exit
} // End of main method
} // End of StringPerformance class