Wednesday, May 2, 2012

Calculate and compare execution time for Map keyset,Map entryset,Poolable String,String Object and String array to List

package oopsConcept;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class ExecutionTimeCalculation{

public static void main(String[] args) {
methodWithObjStr();
methodWithPoolableStr();
methodWithStrArray();
extractDataFromMapUsingEntryset();
extractDataFromMapUsingKeyset();
}


/**
* Extract data from map using entryset.
*/
public static void extractDataFromMapUsingEntryset(){
long startTime = System.nanoTime();
Map map=new HashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
map.put("5", "e");
map.put("6", "f");
for (Iterator> iterator = map.entrySet().iterator(); iterator.hasNext();) {
Entry key = iterator.next();
System.out.println(key.getKey());
System.out.println(key.getValue());
}
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds for extractDataFromMapUsingEntryset:"+ (endTime-startTime));
}


/**
* Extract data from map using keyset.
*/
public static void extractDataFromMapUsingKeyset(){
long startTime = System.nanoTime();
Map map=new HashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
map.put("5", "e");
map.put("6", "f");
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key);
System.out.println(map.get(key));
}
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds for extractDataFromMapUsingKeyset:"+ (endTime-startTime));
}


/**
* Method with obj str.
*/
public static void methodWithObjStr(){
long startTime = System.nanoTime();
ArrayList logoList =new ArrayList();
for (int i = 0; i < 10; i++) { logoList.add(new String()); } System.out.println("methodWithObjStr: "+logoList); long endTime = System.nanoTime(); System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime)); } /** * Method with poolable str. */ public static void methodWithPoolableStr(){ long startTime = System.nanoTime(); ArrayList logoList =new ArrayList();
for (int i = 0; i < 10; i++) { logoList.add(""); } System.out.println("methodWithPoolableStr: "+logoList); long endTime = System.nanoTime(); System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime)); } /** * Method with str array. */ public static void methodWithStrArray(){ long startTime = System.nanoTime(); String s[]=new String[10]; List l=Arrays.asList(s);
System.out.println("methodWithStrArray: "+l);
long endTime = System.nanoTime();
System.out.println("Total elapsed time in nanoseconds:"+ (endTime-startTime));
}
}

No comments:

Post a Comment

Thanks for your comments/Suggestions.