Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Pure Java vs ArrayUtils benchmark issue

By: a guest on Apr 25th, 2013  |  syntax: Java  |  size: 1.85 KB  |  hits: 22  |  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.util.ArrayList;
  6. import java.util.List;
  7.  
  8. /**
  9.  * Benchmarks conversion from List<Integer> to int[] for different
  10.  * size lists using pure java vs Apache Commons ArrayUtils.
  11.  */
  12. public class ArrayUtilsBenchmark
  13. {
  14.     public static void main(String[] args)
  15.     {
  16.         for (int i=5;i<2561;i+=i) {
  17.             ArrayUtilsBenchmark testClass = new ArrayUtilsBenchmark();
  18.             testClass.test(i);
  19.         }
  20.     }
  21.  
  22.     private void test(int numElements) {
  23.  
  24.         List<Integer> list1 = new ArrayList<Integer>(numElements);
  25.         for (int i=0; i<numElements; i++) {
  26.             list1.add(new Integer(i*((int)(Math.random()*100))));
  27.         }
  28.  
  29.         System.out.println("Comparison for " + list1.size() + " elements");
  30.  
  31.         long start1 = System.nanoTime();
  32.         int[] primList1 = convertPureJava(list1);
  33.         final long dur1 = System.nanoTime() - start1;
  34.         System.out.println("pure java:   " + dur1 + " ns");
  35.  
  36.         long start2 = System.nanoTime();
  37.         int[] primList2 = convertArrayUtils(list1);
  38.         final long dur2 = System.nanoTime() - start2;
  39.         System.out.println("array utils: " + dur2 + " ns");
  40.  
  41.         System.out.println("factor: "+dur2/dur1);
  42.         System.out.println("----------------------------");
  43.     }
  44.  
  45.     private static int[] convertPureJava(List<Integer> tutorialIdsList)
  46.     {
  47.         int[] arrayOfInt = new int[tutorialIdsList.size()];
  48.         int i = 0;
  49.  
  50.         for (Integer tutId : tutorialIdsList) {
  51.             arrayOfInt[i] = tutId;
  52.             i++;
  53.         }
  54.  
  55.         return arrayOfInt;
  56.     }
  57.  
  58.     private static int[] convertArrayUtils(List<Integer> tutorialIdsList)
  59.     {
  60.         return ArrayUtils.toPrimitive(tutorialIdsList.toArray(new Integer[tutorialIdsList.size()]));
  61.     }
  62. }