For Loop Performance Test

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ForLoopPerformanceTest{
    private static List<Integer> list = new ArrayList<Integer>();
    private static long          startTime;
    public static void main(String[] args) {
        for (int i = 0; i < 10000000; i++) {
            list.add(i);
        }
        // Java 8 for each
        startTime = Calendar.getInstance().getTimeInMillis();
        list.forEach(e -> {  });
        System.out  .println("Using java 8 for each :: " +
        (Calendar.getInstance().getTimeInMillis() - startTime) + " ms");

        // Type 1
        startTime = Calendar.getInstance().getTimeInMillis();
        for (Integer i : list) {      //   }
        System.out.println("Using For each loop :: " +
       (Calendar.getInstance().getTimeInMillis() - startTime) + " ms");

        // Type 2
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < list.size(); j++) {      //    }
        System.out.println("Using collection.size() :: " +
       (Calendar.getInstance().getTimeInMillis() - startTime) + " ms");

        // Type 3
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for (int j = 0; j < size; j++)  {    //     }
        System.out.println("Using [int size = list.size(); int j = 0; j < size ; j++] :: "
                + (Calendar.getInstance().getTimeInMillis() - startTime) + " ms");
    }
}

Out Put :-
Using java 8for each :: 122 ms
Using For each loop :: 40 ms
Using collection.size() :: 6 ms
Using [int size = list.size(); int j = 0; j < size ; j++] :: 6 ms

Comments

Popular posts from this blog

Spring Boot + Maven + RestFul + JPA + Sqlite

View & Materialized View

JDBC with Sqlite