LoginSignup
2
3

More than 5 years have passed since last update.

[Java] Iteratorと配列の処理時刻比較

Posted at

概要

Javaにおいて,Iteratorと配列に対して,それぞれシーケンシャルにアクセスした場合の処理時間を比較しました.

コード

main.java
import java.util.Iterator;
import java.util.Arrays;
import java.util.ArrayList;


public class main {
    public static void main(String[] args) {
        long t1,t2,t3;
        int l = 100000000;
        long procTimeArray, procTimeIter;
        int counter1 = 0,counter2 = 0;
        Object temp;
        Integer [] array = new Integer [l];
        System.out.println("Array  / Iterator (ms)");
        System.out.println("----------------");

        for(int trial = 0; trial < 10; trial++){
            Iterator it = new ArrayList<Integer>(Arrays.asList(array)).iterator();
            t1 = System.currentTimeMillis();
            for ( int i = 0; i < l; i++ ){
                temp = array[i];
            }
            t2 = System.currentTimeMillis();
            while ( it.hasNext() ){
                temp = it.next();
            }
            t3 = System.currentTimeMillis();

            procTimeIter = (t3 - t2);
            procTimeArray = (t2 - t1);
            System.out.println(procTimeArray+" / "+procTimeIter);
            counter1 += procTimeArray;
            counter2 += procTimeIter;
        }
        System.out.println("----------------");
        System.out.println("Average:" + (int)counter1/10+" / "+(int)counter2/10);
    }

}

結果

Array  / Iterator (ms)
----------------
7 / 19
27 / 18
0 / 16
0 / 14
0 / 14
0 / 14
0 / 14
0 / 14
0 / 19
0 / 14
----------------
Average:3 / 15
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3