How to Test Performance of While Loop, For Loop,Iterator in Java


1.Introduction

Here this example will tell us how to test performance of while loop, for loop, iterator in Java, as shown below.

Source Code

1)abstract class TestRunTime


package com.beginner.examples;

//Simply inherit this class and override the runCode() 
method to get the time

public abstract class TestRunTime {
	
	public long  gettTime()
	{
		long sta r= System.currentTimeMillis();
		runCode();
		long end = System.currentTimeMillis();
		return end - star;
	}
	 
	public abstract void runCode();
	
}

2)

package com.beginner.examples;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class TestWhileIterateExample {

	private static List alList;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String[] testStr = new String[9000000];
		for(int i = 0;i < testStr.length ; i++)
		{
			testStr[i] = "Hello" ;
		}
		alList=Arrays.asList(testStr);
		testFor();
		testWhile();
		testIterate();
		
	}
	
	static void testFor()
	{
		//Create anonymous inner classes
		long time=new TestRunTime() {
			
			@Override
			public void runCode() {
				for(int i=0;i<alList.size();i++)
				{
					String temp=alList.get(i);
					
				}
				
				
			}
		}.gettTime();
		
		System.out.println("For:" + time + "(ms)");
	}
	
	static void testWhile()
	{
		long time = new TestRunTime() {
			
			@Override
			public void runCode() {
			 int i = 0;
			 while(i < alList.size())
			 {
				 String temp = alList.get(i);
				 
				 i++;
			 }
				
				
			}
		}.gettTime();
		System.out.println("While:" + time + "(ms)");
	}
	
	static void testIterate()
	{
		long time = new TestRunTime() {
			
			@Override
			public void runCode() {
				Iterator it=alList.iterator();
				while(it.hasNext())
				{
					String temp=it.next();
					
				}
				
			}
		}.gettTime();
		
		System.out.println("Iterate:"+time+"(ms)");
	}
}

Output:

For:20(ms)
While:19(ms)
Iterate:24(ms)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments