go to  ForumEasy.com   
JavaPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » Java Collections » Collection Sorting: Static vs. Dynamic
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: Collection Sorting: Static vs. Dynamic
EricJ
member
offline   
 
posts: 50
joined: 02/22/2007
from: CA
  posted on: 02/17/2009 08:51:40 PM    Edit  |   Quote  |   Report 
Collection Sorting: Static vs. Dynamic

Static Collection Sorting: java.util.Collections.sort()

public class StaticSorting
{
    public static void main(String[] argv)
    {
        long t1, t2;
        int max = 1000000;
		
        t1=System.currentTimeMillis();
		
        List myList = new ArrayList();
        for(int i=0; i<max; i++){
            myList.add("ABCDEFG"+Math.random()*100000);
        }
        Collections.sort(myList);
		
        t2=System.currentTimeMillis();
		
        Runtime rt = Runtime.getRuntime();
        long memoryUsed = rt.totalMemory() - rt.freeMemory();
        System.out.println(myList.get(0));
        System.out.println("Time consumed="+(t2-t1)+" (ms)   Memory used="+memoryUsed+ "(bytes)" );
    	
    }
}


Here is the output:

ABCDEFG0.3944624056728685
Time consumed=10813 (ms) Memory used=103774088(bytes)

 Profile | Reply Points Earned: 0
EricJ
member
offline   
 
posts: 50
joined: 02/22/2007
from: CA
  posted on: 02/17/2009 09:00:37 PM    Edit  |   Quote  |   Report 
Dynamic Collection Sorting: java.util.TreeSet
public class DynamicSorting
{
    public static void main(String[] argv)
    {
        long t1, t2;
        int max = 1000000;
		
        t1=System.currentTimeMillis();

        TreeSet mySet = new TreeSet();
        for(int i=0; i<max; i++){
            mySet.add("ABCDEFG"+Math.random()*100000);
        }		
		
        t2=System.currentTimeMillis();
		
        Runtime rt = Runtime.getRuntime();
        long memoryUsed = rt.totalMemory() - rt.freeMemory();
        System.out.println(mySet.first());
        System.out.println("Time consumed="+(t2-t1)+" (ms)   Memory used="+memoryUsed+ "(bytes)" );
    	
    }
}



Here is the output:

ABCDEFG0.07930068373074306
Time consumed=17328 (ms) Memory used=124260248(bytes)

 Profile | Reply Points Earned: 0
EricJ
member
offline   
 
posts: 50
joined: 02/22/2007
from: CA
  posted on: 02/17/2009 09:14:39 PM    Edit  |   Quote  |   Report 
Observations:

1) The static way is faster;
2) The static way is more memory efficient.

 Profile | Reply Points Earned: 0

 
Powered by ForumEasy © 2003-2005, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.