Compare the speed of the for statement and the extended for statement.

Introduction

The extended for statement is faster than the normal for statement because it uses Iterator! Someone told me that I left it as it was without checking it. At this time, I decided to investigate it properly. What if it comes to the story that a normal for statement is better ... I think the era is stream, but since my site is Java 6, I have to teach my juniors how to write in Java 6. ~~ It's not because I can't write a stream. ~~

Verification environment

I wrote it

verification code

When I did it at around 100,000, the value was too small to compare, so I looped it 10 million times.

Main.java


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

public class Main {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i < 10000000; i++) {
			list.add(i);
		}

		//start
		long start = System.currentTimeMillis();
		//10 million loops
		for (int i = 0; i < list.size(); i++) {
			int tmp = list.get(i);
		}
		//End
		long end = System.currentTimeMillis();
		System.out.println("for statement: " + (end - start) + " ms");

		//start
		start = System.currentTimeMillis();
		//10 million loops
		for (Integer i : list) {
			int tmp = i;
		}
		//End
		end = System.currentTimeMillis();
		System.out.println("Extended for statement: " + (end - start) + " ms");

	}

}

inspection result

Such an idiot ... I tried it several times, but the extended for statement didn't get faster.

for statement: 24 ms
Extended for statement: 29 ms

Verification ②

When I thought that it wouldn't end as it was, there was a site like this.

Reason for using extended for statement-[Seasar] Diary of soichirooooo5

If you look at the link, the answer you wanted to write in this article is written, It's a big deal, so I'll do it till the end. Since the verification is done only with ArrayList, I will also verify with Array and LinkedList.

Verification code (array)

Main.java


public class Main {

	public static void main(String[] args) {
		int[] array = new int[10000000];
		for (int i = 0; i < 10000000; i++) {
			array[i] = i;
		}

		//start
		long start = System.currentTimeMillis();
		//10 million loops
		for (int i = 0; i < array.length; i++) {
			int tmp = array[i];
		}
		//End
		long end = System.currentTimeMillis();
		System.out.println("for statement: " + (end - start) + " ms");

		//start
		start = System.currentTimeMillis();
		//10 million loops
		for (int i : array) {
			int tmp = i;
		}
		//End
		end = System.currentTimeMillis();
		System.out.println("Extended for statement: " + (end - start) + " ms");

	}

}

result

~~ for sentence too fast www ~~ Because autoboxing was done in the extended for statement I couldn't measure it accurately. The result remains the same.

for statement: 3 ms
Extended for statement: 3 ms

Verification (LinkedList)

Main.java


package qiita;

import java.util.LinkedList;
import java.util.List;

public class Main {

	public static void main(String[] args) {
		List<Integer> list = new LinkedList<>();
		for (int i = 0; i < 10000000; i++) {
			list.add(i);
		}

		//start
		long start = System.currentTimeMillis();
		//10 million loops
		for (int i = 0; i < list.size(); i++) {
			int tmp = list.get(i);
		}
		//End
		long end = System.currentTimeMillis();
		System.out.println("for statement: " + (end - start) + " ms");

		//start
		start = System.currentTimeMillis();
		//10 million loops
		for (Integer i : list) {
			int tmp = i;
		}
		//End
		end = System.currentTimeMillis();
		System.out.println("Extended for statement: " + (end - start) + " ms");

	}

}

inspection result

I haven't received a response for about 5 minutes.

Verification (LinkedList) ②

Since it does not end, re-verify with 100,000 loops

Main.java


import java.util.LinkedList;
import java.util.List;

public class Main {

	public static void main(String[] args) {
		List<Integer> list = new LinkedList<>();
		for (int i = 0; i < 100000; i++) {
			list.add(i);
		}

		//start
		long start = System.currentTimeMillis();
		//10 million loops
		for (int i = 0; i < list.size(); i++) {
			int tmp = list.get(i);
		}
		//End
		long end = System.currentTimeMillis();
		System.out.println("for statement: " + (end - start) + " ms");

		//start
		start = System.currentTimeMillis();
		//10 million loops
		for (Integer i : list) {
			int tmp = i;
		}
		//End
		end = System.currentTimeMillis();
		System.out.println("Extended for statement: " + (end - start) + " ms");

	}

}

Verification result ②

it's amazing! !!

for statement: 5695 ms
Extended for statement: 36 ms

Finally

It turned out that the ordinary for statement is faster for things that operate in order from the front, such as ArrayList and arrays. However, the Linked List made an overwhelming difference. It's strange to care about the entity when looping the List interface, so I think I've come to the conclusion that an extended for statement is fine.

The following is a quote from the reference site.

If you use the extended for statement, you don't have to worry about "99% or more performance degradation" even if you don't know whether the object passed to the for statement is an ArrayList or a LinkedList.

Also, the extended for statement converts the implementation type of the List interface into code that uses an iterator, and in the case of an array, it converts it into code that accesses the index.

You can see that the translation of this compiler will generate the appropriate code for the list or array you pass to the for statement. In other words, if you use Extended for, you don't have to think about anything and you don't have to worry about anything. If something goes wrong, it will do something behind the API.

In other words, you can use the extended for statement without thinking about anything. stream Let's study.

Recommended Posts

Compare the speed of the for statement and the extended for statement.
Comparison of processing speed between Stream including cast and extended for statement
[Java] for statement / extended for statement
I tried to measure and compare the speed of GraalVM with JMH
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
[For beginners] DI ~ The basics of DI and DI in Spring ~
About for statement and if statement
[Java] Make variables in extended for statement and for Each statement immutable
The idea of C # (lambda expression, for statement) to chew
This and that of the JDK
Compare driving ① and the other two driving
Utilization of Java array elements, for, length, value, and extended for statements
How to get the contents of Map using for statement Memorandum
Set the number of seconds for fast forward and rewind in ExoPlayer
Folding and unfolding the contents of the Recyclerview
About the operation of next () and nextLine ()
Compare the elements of an array (Java)
must not return in the for statement
[Ruby basics] About the role of true and break in the while statement
[Java] Nowadays, the extended for statement is not exclusively for List, isn't it?
About the mechanism of the Web and HTTP
Until you understand that the extended for statement and the for statement using length are the same process (handle multidimensional arrays)
[Rails] Articles for beginners to organize and understand the flow of form_with
Reference information for investigating and analyzing the memory usage status of Tomcat
Basics of java basics ② ~ if statement and switch statement ~
Check the version of the JDK installed and the version of the JDK enabled
Think about the combination of Servlet and Ajax
Zeller's official (asking for the day of the week)
Points for coexistence of devise and devise token auth
[Java] The confusing part of String and StringBuilder
Implement the star five function using the for statement
[Note] Java: Measures the speed of string concatenation
I compared the characteristics of Java and .NET
Array vs ArrayList vs HashMap Extended for Statement Race
Criteria for proper use of render and redirect_to
Learn the rudimentary mechanism and usage of Gradle 4.4
About next () and nextLine () of the Scanner class
What are the advantages of DI and Thymeleaf?
How to specify index of JavaScript for statement
[Ruby] Setting values ​​and memorandum for the table
Java for statement
ArrayList and the role of the interface seen from List
Please note the division (division) of java kotlin Int and Int
The comparison of enums is ==, and equals is good [Java]
[For beginners] Quickly understand the basics of Java 8 Lambda
[Grails] About the setting area and the setting items of application.yml
Speed comparison at the time of generation at the time of date conversion
Convert the array of errors.full_messages to characters and output
Rewrite the code for java.io.File with java.nio.Path and java.nio.Files
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
[CentOS] Download and build the specified version of Git
Until the use of Spring Data and JPA Part 2
Compare the difference between dockerfile before and after docker-slim
Learn for the first time java # 3 expressions and operators
Verification of the relationship between Docker images and containers
Until the use of Spring Data and JPA Part 1
I summarized the types and basics of Java exceptions
I tried using an extended for statement in Java
List of frequently used Java instructions (for beginners and beginners)
Prepare the environment for java11 and javaFx with Ubuntu 18.4