java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
ArrayList LinkedList
Code
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* ArrayList LinkedList 多種遍歷性能測試
*
* @author chigusa
* @function
* @date 2017/9/25
*/
@FixMethodOrder(MethodSorters.JVM)
public class ListSpeedTest {
private static final int NUM = 100000;
private List<Integer> arrayList;
private List<Integer> linkedList;
private Integer temp;
@Before
public void init() {
arrayList = new ArrayList<>(NUM);
linkedList = new LinkedList<>();
for (int i = 0; i < NUM; i++) {
arrayList.add(Integer.MAX_VALUE);
linkedList.add(Integer.MAX_VALUE);
}
}
@Test
public void forArrayList() {
for (int i = 0; i < NUM; i++) {
temp = arrayList.get(i);
}
}
@Test
public void forLinkedList() {
for (int i = 0; i < NUM; i++) {
temp = linkedList.get(i);
}
}
@Test
public void iteratorInArrayList() {
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
temp = iterator.next();
}
}
@Test
public void iteratorInLinkedList() {
Iterator<Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
temp = iterator.next();
}
}
@Test
public void forEachArrayList() {
for (Integer i : arrayList) {
temp = i;
}
}
@Test
public void forEachLinkedList() {
for (Integer i : linkedList) {
temp = i;
}
}
@Test
public void java8forEachArrayList() {
arrayList.forEach(integer -> temp = integer);
}
@Test
public void java8forEachLinkedList() {
arrayList.forEach(integer -> temp = integer);
}
}
結(jié)果
HashMap
Code
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* HashMap 遍歷方法性能測試
*
* @author chigusa
* @function
* @date 2017/9/25
*/
@FixMethodOrder(MethodSorters.JVM)
public class HashMapTest {
private static final int NUM = 100000;
private HashMap<Integer, Integer> hashMap;
private Integer k, v;
@Before
public void init() {
hashMap = new HashMap<>(NUM);
for (int i = 0; i < NUM; i++) {
hashMap.put(i, i);
}
}
@Test
public void forEachKeySet() {
for (Integer i : hashMap.keySet()) {
k = i;
v = hashMap.get(i);
}
}
@Test
public void forEachEntitySet() {
for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
k = entry.getKey();
v = entry.getValue();
}
}
@Test
public void iterator() {
Iterator<Map.Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> entry = iterator.next();
k = entry.getKey();
v = entry.getValue();
}
}
@Test
public void java8ForEach() {
hashMap.forEach((k, v) -> {
this.k = k;
this.v = v;
});
}
}