1. 程式人生 > >ArrayList的不同的遍歷方式性能比較,其實都差不了多少

ArrayList的不同的遍歷方式性能比較,其實都差不了多少

ces span new import oop for pan .get long

//RadomAcess的接口for..i的遍歷比for..loop的快,@more see comments for interface RandomAcess 
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ListPerformanceTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for(int i = 0; i < Integer
.MAX_VALUE / 200; i++) { list.add("1"); } long d1 = System.currentTimeMillis(); /***************** fastest ************************/ // for(int i = 0, n = list.size(); i < n; i++) { // list.get(i); // } /***************** second fastest due to each loop would get the list size ************************/ // for(int i = 0; i < list.size(); i++) { // list.get(i); // } /***************** not know why this is faster than the last ************************/ // for(Iterator<?> it = list.iterator(); it.hasNext();) { // it.next(); // } // for(String s : list) { // if(s != null) { // continue; // } // } System
.out.println("Times(ms):" + (System.currentTimeMillis() - d1)); } }

ArrayList的不同的遍歷方式性能比較,其實都差不了多少