Java performance tips - lets share :D

Soldato
Joined
15 Nov 2008
Posts
5,060
Location
In the ether
There seems to be quite a few Java threads around so I thought I'd suggest a thread to share some performance tips.

Here's a quickie. Try to use a StringTokenizer over a split:

Code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;


public class strT {
	static String temp="";
	static long startTime = System.currentTimeMillis();
	static long stopTime = System.currentTimeMillis();
	public static void main(String args[]){	

		
		startTime = System.currentTimeMillis();
		
		for(int i=0; i<1000000; i++){
		StringTokenizer st = new StringTokenizer("poo,boo",",");
			while(st.hasMoreTokens()){
		
				temp = st.nextToken();
			}
		}
		stopTime = System.currentTimeMillis();
		System.out.println(stopTime-startTime+" Milliseconds");
	
		
		String testString ="poo,boo"; 
		
		startTime = System.currentTimeMillis();
		
		for(int i=0; i<1000000; i++){
			String elements[] = testString.split(",");
			for(int k=0;k<elements.length;k++){
				
				temp = elements[k];
			}
		}
		stopTime = System.currentTimeMillis();
		System.out.println(stopTime-startTime+" Milliseconds");	
	
	}
}

Results:

849 Milliseconds
3896 Milliseconds

Not sure that's such a great way to test that, but hey.

Anyone got a tip they want to share?
 
Back
Top Bottom