1 /*
2  * Copyright (C) 2013 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.collect;
16 
17 import com.google.caliper.BeforeExperiment;
18 import com.google.caliper.Benchmark;
19 import com.google.caliper.Param;
20 import java.util.Arrays;
21 import java.util.Comparator;
22 import java.util.Random;
23 
24 /**
25  * A benchmark to determine the overhead of sorting with {@link Ordering#from(Comparator)}, or with
26  * {@link Ordering#natural()}, as opposed to using the inlined {@link Arrays#sort(Object[])}
27  * implementation, which uses {@link Comparable#compareTo} directly.
28  *
29  * @author Louis Wasserman
30  */
31 public class ComparatorDelegationOverheadBenchmark {
32   private final Integer[][] inputArrays = new Integer[0x100][];
33 
34   @Param({"10000"})
35   int n;
36 
37   @BeforeExperiment
setUp()38   void setUp() throws Exception {
39     Random rng = new Random();
40     for (int i = 0; i < 0x100; i++) {
41       Integer[] array = new Integer[n];
42       for (int j = 0; j < n; j++) {
43         array[j] = rng.nextInt();
44       }
45       inputArrays[i] = array;
46     }
47   }
48 
49   @Benchmark
arraysSortNoComparator(int reps)50   int arraysSortNoComparator(int reps) {
51     int tmp = 0;
52     for (int i = 0; i < reps; i++) {
53       Integer[] copy = inputArrays[i & 0xFF].clone();
54       Arrays.sort(copy);
55       tmp += copy[0];
56     }
57     return tmp;
58   }
59 
60   @Benchmark
arraysSortOrderingNatural(int reps)61   int arraysSortOrderingNatural(int reps) {
62     int tmp = 0;
63     for (int i = 0; i < reps; i++) {
64       Integer[] copy = inputArrays[i & 0xFF].clone();
65       Arrays.sort(copy, Ordering.natural());
66       tmp += copy[0];
67     }
68     return tmp;
69   }
70 
71   private static final Comparator<Integer> NATURAL_INTEGER =
72       new Comparator<Integer>() {
73         @Override
74         public int compare(Integer o1, Integer o2) {
75           return o1.compareTo(o2);
76         }
77       };
78 
79   @Benchmark
arraysSortOrderingFromNatural(int reps)80   int arraysSortOrderingFromNatural(int reps) {
81     int tmp = 0;
82     for (int i = 0; i < reps; i++) {
83       Integer[] copy = inputArrays[i & 0xFF].clone();
84       Arrays.sort(copy, Ordering.from(NATURAL_INTEGER));
85       tmp += copy[0];
86     }
87     return tmp;
88   }
89 }
90