StringBuilder is faster one among string, stringbuffer and stringbuilder.
Example
public class Main { long startTime = 0l; long endTime = 0l; long timeDiff = 0l; // Concatenates to String public void concat1(String website) { startTime = System.nanoTime(); website = website + ".com"; endTime = System.nanoTime(); timeDiff = endTime - startTime; System.out.println("Time taken by String: " + timeDiff); } // Concatenates to StringBuilder public void concat2(StringBuilder website) { startTime = System.nanoTime(); website.append(".com"); endTime = System.nanoTime(); timeDiff = endTime - startTime; System.out.println("Time taken by StringBuilder: " + timeDiff); } // Concatenates to StringBuffer public void concat3(StringBuffer website) { startTime = System.nanoTime(); website.append(".com"); endTime = System.nanoTime(); timeDiff = endTime - startTime; System.out.println("Time taken by StringBuffer: " + timeDiff); } public static void main(String[] args) { Main object = new Main(); String s1 = "w3schools"; object.concat1(s1); StringBuilder s2 = new StringBuilder("w3schools"); object.concat2(s2); StringBuffer s3 = new StringBuffer("w3schools"); object.concat3(s3); } } |
Output
Time taken by String: 19199 Time taken by StringBuilder: 910 Time taken by StringBuffer: 3650 |