In this tutorial it is given that StringBuffer is synchronized and StringBuilder is not
Can a class be synchonized ?
I know that synchronized methods are locked for particular thread and non synchronized are not.But how does a performance of the programe is increased with non-syncronized method?
Code from here
public class Main { public static void main(String[] args) { int N = 77777777; long t; { StringBuffer sb = new StringBuffer(); t = System.currentTimeMillis(); for (int i = N; i --> 0 ;) { sb.append(""); } System.out.println(System.currentTimeMillis() - t); } { StringBuilder sb = new StringBuilder(); t = System.currentTimeMillis(); for (int i = N; i --> 0 ;) { sb.append(""); } System.out.println(System.currentTimeMillis() - t); } } }
gives the numbers of
2241 ms
forStringBuffer
vs753 ms
forStringBuilder
.
and accoding to this the extracode is the synchronised keyword in StringBuffer.Does this synchronised keyword cost the extra 1488ms and if so then should we always prefer StringBuilder instead of StringBuffer?
Thanks in advance.