Saturday, July 28, 2012

StringBuilder vs StringBuffer

StringBuilder was added in JDK 1.5 and is not synchronized and hence is fast, while StringBuffer comes from earlier versions and is synchronized and therefore is slower.Otherwise all the methods of StringBuilder are the same as StringBuffer.
package pack2;
import java.lang.*;
import java.io.*;
import java.util.*;

public class BuilderVsBuffer {
    public static void main(String[] args) {
        int loops = 123456;
        long t;
        {
            StringBuilder sb = new StringBuilder();
            t = System.currentTimeMillis();
            for (int i = loops; i-->0;) {
                sb.append(" ");
            }
            System.out.println("StringBuffy.. I am very fast You See I have taken Only "+ (System.currentTimeMillis() - t) + " MilliSeconds" );
        }
        {
            StringBuffer sb = new StringBuffer();
            t = System.currentTimeMillis();
            for (int i = loops; i-->0;) {
                sb.append(" ");
            }
            System.out.println("unforntly, u are the Gen 1.5x , but ppl trust me Since i'm thread safe(have a acount in synchronized Locker) @" + (System.currentTimeMillis() - t) + "MilliSeconds");
        }
    }
}
The Result is
----------------------
StringBuffy.. I am very fast You See I have taken Only 31 MilliSeconds
unforntly, u are the Gen 1.5x , but ppl trust me Since i'm thread safe(have a acount in synchronized Locker) @62MilliSeconds

No comments:

Post a Comment