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 
21 import java.util.Arrays;
22 import java.util.Comparator;
23 import java.util.Random;
24 
25 /**
26  * A benchmark to determine the overhead of sorting with {@link Ordering#from(Comparator)}, or with
27  * {@link Ordering#natural()}, as opposed to using the inlined {@link Arrays#sort(Object[])}
28  * implementation, which uses {@link Comparable#compareTo} directly.
29  *
30  * @author Louis Wasserman
31  */
32 public class ComparatorDelegationOverheadBenchmark {
33   private final Integer[][] inputArrays = new Integer[0x100][];
34 
35   @Param({"10000"})
36   int n;
37 
38   @BeforeExperiment
setUp()39   void setUp() throws Exception {
40     Random rng = new Random();
41     for (int i = 0; i < 0x100; i++) {
42       Integer[] array = new Integer[n];
43       for (int j = 0; j < n; j++) {
44         array[j] = rng.nextInt();
45       }
46       inputArrays[i] = array;
47     }
48   }
49 
arraysSortNoComparator(int reps)50   @Benchmark 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 
arraysSortOrderingNatural(int reps)60   @Benchmark int arraysSortOrderingNatural(int reps) {
61     int tmp = 0;
62     for (int i = 0; i < reps; i++) {
63       Integer[] copy = inputArrays[i & 0xFF].clone();
64       Arrays.sort(copy, Ordering.natural());
65       tmp += copy[0];
66     }
67     return tmp;
68   }
69 
70   private static final Comparator<Integer> NATURAL_INTEGER = new Comparator<Integer>() {
71     @Override
72     public int compare(Integer o1, Integer o2) {
73       return o1.compareTo(o2);
74     }
75   };
76 
arraysSortOrderingFromNatural(int reps)77   @Benchmark int arraysSortOrderingFromNatural(int reps) {
78     int tmp = 0;
79     for (int i = 0; i < reps; i++) {
80       Integer[] copy = inputArrays[i & 0xFF].clone();
81       Arrays.sort(copy, Ordering.from(NATURAL_INTEGER));
82       tmp += copy[0];
83     }
84     return tmp;
85   }
86 }
87