for那种方式效率最高

网友投稿 827 2022-10-26

for那种方式效率最高

for那种方式效率最高

package com.data.struct;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class Test2 { public static void main(String[] args) { List list = new ArrayList(); int runTime = 1000;//执行次数 for (int i = 0; i < 1000 * 1000; i++) { list.add(i); } int size = list.size(); long currTime = System.currentTimeMillis();//开始分析前的系统时间 //基本的for for(int j = 0; j < runTime; j++) { for (int i = 0; i < size; i++) { list.get(i); } } long time1 = System.currentTimeMillis(); //foreach for(int j = 0; j < runTime; j++) { for (Integer integer : list) { } } long time2 = System.currentTimeMillis(); for(int j = 0; j < runTime; j++) { //while int i = 0 ; while(i < size){ list.get(i++); } } long time3 = System.currentTimeMillis(); for(int j = 0; j < runTime; j++) {//普通for循环 for (int i = 0; i < list.size(); i++) { list.get(i); } } long time4 = System.currentTimeMillis(); for(int j = 0; j < runTime; j++) {//迭代 Iterator iter = list.iterator(); while(iter.hasNext()) { iter.next(); } } long time5 = System.currentTimeMillis(); long time = time1 - currTime ; System.out.print("use for:" + time); time = time2 - time1; System.out.print("\tuse foreach:" + time); time = time3 - time2; System.out.print("\tuse while:" + time); time = time4 - time3; System.out.print("\tuse for2:" + time); time = time5 - time4; System.out.print("\tuse iterator:" + time); System.out.println(); }}

use for:6035 use foreach:13345 use while:5930 use for2:9853 use iterator:11767

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:godropbox - 来自Dropbox用于编写Go服务/应用程序的公共库
下一篇:求线性方程组的解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~