Array vs ArrayList vs HashMap Extended for Statement Race

correction

The comparison operator was wrong (fixed)

What was used

・ Java9 ・ Eclipse

Motivation

I wonder which one is the fastest if I set aside what is best and turn it with an extended for statement.

result

ForEaerVs.java


public class ForEaerVs {
	public static void main(String[] argS) {

		Integer mm;
		
		//Array
		Integer[] arry = new Integer[1000000000];

		for (Integer i = 0 ; i < 1000000000; i++) {
			Integer arryInt = i;
			arry[i] = arryInt;
		}
		long staetTimeArry = System.nanoTime();
			for(Integer iA : arry) {
				mm = iA;
			}
		long endTimeArry = System.nanoTime();
		System.out.println("Array speed:" + (endTimeArry -staetTimeArry));

		// List
		List<Integer> list = new ArrayList<Integer>();
		for (Integer j = 0 ; j < 1000000000; j++) {
			Integer arryInt = j;
			list.add(arryInt);
		}
		long staetTimeList = System.nanoTime();
			for (Integer iL: list) {
				mm = iL;
			}
		long endTimeList = System.nanoTime();
		System.out.println("List speed:" + (endTimeList -staetTimeList));

		
		// HushMap
		HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
		for (Integer k = 0 ; k < 1000000000; k++) {
			Integer arryInt = k;
			hash.put(k, arryInt);
		}
		long staetTimeHash = System.nanoTime();
			for (Integer iH : hash.values()) {
				mm = iH;
			}
		long endTimeHash = System.nanoTime();
		System.out.println("Hash speed:" + (endTimeHash -staetTimeHash));

	}
}

ForEaerVsResult.java


Array speed: 4020600
List speed: 11350400
Hash speed: 18974400

The result including the creation time is as follows

ForEaerVsPlusCreateResult.java


Array speed: 35613700
List speed: 98473300
Hash speed: 121742700

Impressions

Although each has different uses, is the array so slow? </ s> Worship the awesomeness of the array seniors

add to

I also tried it with Linked List

ForEaerVsResult.java


Array speed: 4001200
List speed: 9521900
Hash speed: 19611200
Linked speed: 15211300

The result including the creation time is as follows

ForEaerVsPlusCreateResult.java


Array speed: 32542100
List speed: 80343600
Hash speed: 101256200
Linked speed: 140576800

Recommended Posts

Array vs ArrayList vs HashMap Extended for Statement Race
[Java] for statement / extended for statement
[Java] How to turn a two-dimensional array with an extended for statement
[Java] How to get HashMap elements by loop control using extended for statement
Compare the speed of the for statement and the extended for statement.
How to use an array for HashMap keys
Java for statement
I tried using an extended for statement in Java
[Beginner] Java variable / logical operator / extended for statement [Note 22]
How to loop Java Map (for Each / extended for statement)