+ 2

java stringbuffer vs string

can someone plz explain how the following code is being working::: public class ConcatTest{ public static String concatWithString() { String t = "Java"; for (int i=0; i<10000; i++){ t = t + "Tpoint"; } return t; } public static String concatWithStringBuffer(){ StringBuffer sb = new StringBuffer("Java"); for (int i=0; i<10000; i++){ sb.append("Tpoint"); } return sb.toString(); } public static void main(String[] args){ long startTime = System.currentTimeMillis(); concatWithString(); System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms"); startTime = System.currentTimeMillis(); concatWithStringBuffer(); System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms"); } } output is: Time taken by Concating with String: 578ms Time taken by Concating with StringBuffer: 0ms

24th Dec 2016, 7:09 PM
Shubham Mittal
Shubham Mittal - avatar
4 odpowiedzi
+ 1
but 0 ms in string buffer.,,, how could this even possible
25th Dec 2016, 7:39 AM
Shubham Mittal
Shubham Mittal - avatar
0
this code show you if you use String Buffer to add line's for your String ,it is faster than String sorry for my bad English i cant explain in English very much
24th Dec 2016, 9:08 PM
Bayram Akdemir
0
in nanosecond this is possible
25th Dec 2016, 7:43 AM
Bayram Akdemir
0
Hi, It's possible. String is immutable, so whenever you try to add a string it creates a new instance which takes time whereas StringBuffer is mutable and consumes less memory. This is why StringBuffer is faster and String is slower.
25th Dec 2016, 6:28 PM
Yukeshkumar N
Yukeshkumar N - avatar