This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Pure Java vs ArrayUtils benchmark issue

By: a guest on Apr 25th, 2013  |  syntax: Java  |  size: 2.06 KB  |  views: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package my.super.duper.test.package;
  2.  
  3. import org.apache.commons.lang.ArrayUtils;
  4.  
  5. import java.text.DecimalFormat;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. /**
  10.  * Benchmarks conversion from List<Integer> to int[] for different
  11.  * size lists using pure java vs Apache Commons ArrayUtils.
  12.  */
  13. public class ArrayUtilsBenchmark
  14. {
  15.     private final static DecimalFormat DF = new DecimalFormat("#.##");
  16.  
  17.     public static void main(String[] args)
  18.     {
  19.         // run loops 1M times to warm up
  20.         ArrayUtilsBenchmark test = new ArrayUtilsBenchmark();
  21.         test.test(1000000);
  22.  
  23.         for (int i=2;i<2561;i+=i) {
  24.             ArrayUtilsBenchmark testClass = new ArrayUtilsBenchmark();
  25.             testClass.test(i);
  26.         }
  27.     }
  28.  
  29.     private void test(int numElements) {
  30.  
  31.         List<Integer> list1 = new ArrayList<Integer>(numElements);
  32.         for (int i=0; i<numElements; i++) {
  33.             list1.add(new Integer(i*((int)(Math.random()*100))));
  34.         }
  35.  
  36.         System.out.println("Comparison for " + list1.size() + " elements");
  37.  
  38.         long start1 = System.nanoTime();
  39.         int[] primList1 = convertPureJava(list1);
  40.         final double dur1 = System.nanoTime() - start1;
  41.         System.out.println("pure java:   " + (long)dur1 + " ns");
  42.  
  43.         long start2 = System.nanoTime();
  44.         int[] primList2 = convertArrayUtils(list1);
  45.         final double dur2 = System.nanoTime() - start2;
  46.         System.out.println("array utils: " + (long)dur2 + " ns");
  47.  
  48.         System.out.println("factor: "+ DF.format(dur1/dur2));
  49.         System.out.println("----------------------------");
  50.     }
  51.  
  52.     private static int[] convertPureJava(List<Integer> list)
  53.     {
  54.         int[] arrayOfInt = new int[list.size()];
  55.         int i = 0;
  56.  
  57.         for (Integer tutId : list) {
  58.             arrayOfInt[i] = tutId;
  59.             i++;
  60.         }
  61.  
  62.         return arrayOfInt;
  63.     }
  64.  
  65.     private static int[] convertArrayUtils(List<Integer> list)
  66.     {
  67.         return ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()]));
  68.     }
  69. }
clone this paste RAW Paste Data