1. 程式人生 > >持有對象---Arrays.asList()和Collections.addAll()的性能比較

持有對象---Arrays.asList()和Collections.addAll()的性能比較

args long 放大 lec ava int imp return slist

    • import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.Collections;
      import java.util.List;
      public class ArraysCompareCollectionsTest {
      public static void main(String[] args) {
      int count = 10000000;//通過改變循環次數來放大或放小結果
      System.out.println("Arrays‘s time is " + arraysTest(count));
      System.out.println("Collections‘s time is " + collectionsTest(count));
      }
      public static long arraysTest(int count) {
      long startTime = System.currentTimeMillis();
      for (int i = 0; i < count; i++) {
      List arrays = new ArrayList ();
      arrays.addAll(Arrays.asList("hello", "java", "world"));
      }
      return System.currentTimeMillis() - startTime;
      }public static long collectionsTest(int count) {
      long startTime = System.currentTimeMillis();
      for (int i = 0; i < count; i++) {
      List arrays = new ArrayList ();
      Collections.addAll(arrays,"hello", "java", "world");
      }
      return System.currentTimeMillis() - startTime;
      }
      }

      二、控制臺輸出結果分析


      1.當count=100000時,Collections的運行速度比Arrays的要快60ms左右


      2.當count=1000000時,Collections的運行速度比Arrays的要快100ms左右


      3.當count=10000000時,Collections的運行速度比Arrays的要快更多

持有對象---Arrays.asList()和Collections.addAll()的性能比較