import java.util.Date;

public class StringTest {    
    public static void main(String[] args) {
    	StringTest stringTest = new StringTest();
    	stringTest.testStringAppend(10000);
    	stringTest.testStringBufferAppend(10000);
    	stringTest.testStringAppend(10000);
    	stringTest.testStringBufferAppend(10000);
    	
    	stringTest.testStringNew(10000);
    	stringTest.testStringBufferNew(10000);
    	stringTest.testStringNew(10000);
    	stringTest.testStringBufferNew(10000);
    	
    	stringTest.testStringReplace5Chars(10000);
    	stringTest.testStringBufferReplace5Chars(10000);
    	stringTest.testStringReplace5Chars(10000);
    	stringTest.testStringBufferReplace5Chars(10000);
    }   
    
    private void testStringAppend(int loopNum) {
    	Date startDate = new Date();
    	String prefixString = "A";
    	for (int i = 0; i< loopNum; i++) {
    		prefixString = prefixString + i;
    	}
    	Date endDate = new Date();
    	printTime("StringAppend", startDate, endDate);
    }
    
    private void testStringNew(int loopNum) {
    	Date startDate = new Date();
    	String newString;
    	for (int i = 0; i< loopNum; i++) {
    		newString = "B";
    	}
    	Date endDate = new Date();
    	printTime("StringNew", startDate, endDate);
    }
    
    private void testStringBufferAppend(int loopNum) {
    	Date startDate = new Date();
    	StringBuffer prefixString = new StringBuffer("A");
    	for (int i = 0; i< loopNum; i++) {
    		prefixString.append(i);
    		prefixString.toString();
    	}
    	Date endDate = new Date();
    	printTime("StringBufferAppend", startDate, endDate);
    }
    
    private void testStringBufferNew(int loopNum) {
    	Date startDate = new Date();
    	StringBuffer prefixString = new StringBuffer("A");
    	for (int i = 0; i< loopNum; i++) {
    		prefixString.replace(0,1,"B");    		
    		prefixString.toString();
    	}
    	Date endDate = new Date();
    	printTime("StringBufferNew", startDate, endDate);
    }
    
    private void testStringReplace5Chars(int loopNum) {
    	Date startDate = new Date();
    	String prefixString = "AAAAABBBBB";
    	for (int i = 0; i< loopNum; i++) {
    		prefixString = prefixString.replaceFirst("BBBBB", "BBBBB");
    	}
    	Date endDate = new Date();
    	printTime("StringReplace5Chars", startDate, endDate);
    }
    
    private void testStringBufferReplace5Chars(int loopNum) {
    	Date startDate = new Date();
    	StringBuffer prefixString = new StringBuffer("AAAAABBBBB");
    	for (int i = 0; i< loopNum; i++) {
    		prefixString.replace(0,5,"BBBBB");    		
    		prefixString.toString();
    	}
    	Date endDate = new Date();
    	printTime("StringBufferReplace5Chars", startDate, endDate);
    }
       
    private void printTime(String methodName, Date startDate, Date endDate) {    	
    	long millis = endDate.getTime() - startDate.getTime();
    	System.out.println(methodName + " took " + millis + " milliseconds ");
    }
}