「Java入門」LinkedListのfor文とforeach文の実行速度テストサンプル
1.Employeeクラス
package sample;
public class Employee {
private String name;
private Integer age;
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}
2.for文とforeach文の効率を比較する
import java.util.LinkedList;
import java.util.List;
public class LinkedListDemo {
public static void main(String[] args) {
List<Employee> cft = new LinkedList<Employee>();
int maxNum = 50000;
for (int i = 0; i < maxNum; i++) {
cft.add(new Employee(“山田" + i, i));
}
int lstSize = cft.size();
String findName = “山田777";
// forループ
long beiginTime = System.currentTimeMillis();
for (int i = 0; i < lstSize; i++) {
Employee val = cft.get(i);
if (findName.equals(val.getName())) {
System.out.println(“for loop test");
}
}
long endTime = System.currentTimeMillis();
// foreachループ
long beginTime2 = System.currentTimeMillis();
for (Employee emp : cft) {
if (findName.equals(emp.getName())) {
System.out.println(“foreach loop test");
}
}
long endTime2 = System.currentTimeMillis();
// 実行結果
System.out.println(“for 実行結果: " + (endTime – beiginTime));
System.out.println(“forearch実行結果: " + (endTime2 – beginTime2));
}
}
3.テスト結果
for loop test
foreach loop test
for 実行結果: 3704
forearch実行結果: 2