Pacific-Design.com

    
Home Index

1. Algorithms

2. String Builder

Algorithms / String Builder /

String vs. StringBuilder

public class LargeString {

    public static void main(String[] args) {
            plainString();  
            plainStringBuilder();
    }
    /*--------------------------------------------------------------------------------------------*/
    public static void plainString() {
        long start = System.currentTimeMillis();
        String res = "";
        
        for(int i=0; i<100000; i++) {
            res += i;
        }
        
        long end = System.currentTimeMillis();
        System.out.println("Plain String = " + (end-start) + " milliseconds" );
    }
    /*--------------------------------------------------------------------------------------------*/          
    public static void plainStringBuilder() {
        long start = System.currentTimeMillis();
        StringBuilder res = new StringBuilder();
        
        for(int i=0; i<100000; i++) {
            res.append(i);
        }
        
        long end = System.currentTimeMillis();
        System.out.println("String Builder = " + (end-start) + " milliseconds" );
    }
    /*--------------------------------------------------------------------------------------------*/    
}

/*
Output

Plain String = 9223 milliseconds
String Builder = 5 milliseconds
*/