Android开发中编码性能问题之for-each

在以往的开发中有些东西没有注意到,这里特意记录下。
for-each增强型循环,做开发的都不会陌生,简单来说for-each比较简洁提高遍历效率。以往我们遍历循环都是如下:

List<String> testList = new ArrayList<String>();
        for(int i = 0; i < testList.size(); i++){
            System.out.print("test: "+testList.get(i));
        }

普遍认为提高效率写法for-each

List<String> testList = new ArrayList<String>();
        for(String str : testList){
            System.out.print("test: " +str);
        }

自从学编程开始,很多人都觉得for-each比较简洁方便效率高,所以很多时候潜意识里也认为for-each真的效率高,我以前也没注意这个,在做android开发的时候基本上很多地方用的for-each,但真的for-each效率比普通循环效率要高?看下面测试结果

new Thread(new Runnable() {

            @Override
            public void run() {
                // arraylist 测试
                List list = new ArrayList();
                for(int i = 0; i< 10000 ;i ++){
                    list.add("de: "+i);
                }
                // for eacth
                String strddd = "";
                long ecathSystemTime = System.currentTimeMillis();
                for(String str: list){
                    strddd = strddd + str;
                }
                System.out.println("eacth time : " + (System.currentTimeMillis() - ecathSystemTime));

                String dddStr = "";
                ecathSystemTime = System.currentTimeMillis();
                for (int i = 0 ; i < list.size(); i++){
                    dddStr = dddStr + list.get(i);
                }
                System.out.println("for time : " + (System.currentTimeMillis() - ecathSystemTime));


                // ---------数组测试
                String[] arrayTest = new String[10000];
                for(int i = 0; i< arrayTest.length ; i++){
                    arrayTest[i] = "test" + i;
                }

                // for eacth
                String arrayStr = "";
                ecathSystemTime = System.currentTimeMillis();
                for(String str: arrayTest){
                    arrayStr = arrayStr + str;
                }
                System.out.println("array eacth time : " + (System.currentTimeMillis() - ecathSystemTime));

                String arrayddStr = "";
                ecathSystemTime = System.currentTimeMillis();
                for (int i = 0 ; i < list.size(); i++){
                    arrayddStr = arrayddStr + list.get(i);
                }
                System.out.println("array for time : " + (System.currentTimeMillis() - ecathSystemTime));
            }
        }).start();

Android开发中编码性能问题之for-each_第1张图片

是不是颠覆了很多人潜意识里的for-each?在遍历List,ArrayList时,for-each的效率远远比不上普通的循环,而遍历其它方式时for-each的效率是比普通循环效率要快的。所以,在遍历ArrayList, List时请用普通的循环,请用普通的循环,请用普通的循环!重要的事情说三遍…

你可能感兴趣的:(Android学习开发,性能,编码,arraylist,android)