Monday, January 28, 2013

Java :: String Builder VS String Buffer

String Builder VS String Buffer

StringBuffer is synchronized, StringBuilder is not, So off course string builder is faster.

And applying the following example using i7 processor and 8 GB ram:


public static void main(String args[]) {
long startTime = System.currentTimeMillis();
//StringBuffer concat = new StringBuffer();
StringBuilder concat = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
concat.append(i);
}
long endTime = System.currentTimeMillis();
System.out.print("length: " + concat.length());
System.out.println(" time: " + (endTime - startTime));
}

will returns the following:

Using String Builder 47 Milliseconds.
Using String Buffer  57 Milliseconds.

Soooo, why to use the "String Buffer"??

as mentioned string buffer is synchronized, and that's means what???
It means that string buffer during appending will have to do a new task which is checking and making sure that only one instance is appending to the buffer at the same exact moment, so if you felt that your system will face that case -appending at the same time- you SHOULD use string buffer.

Have a blessed day :)

1 comment:

  1. Wonderful idea to write something on Java programming especially about its coding. I like this idea and very much impressed.

    ReplyDelete