• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.collect;
18 
19 import com.google.caliper.Benchmark;
20 import com.google.caliper.Param;
21 
22 import java.util.List;
23 
24 /**
25  * Benchmark for various ways to create an {@code ImmutableList}.
26  *
27  * @author Louis Wasserman
28  */
29 public class ImmutableListCreationBenchmark {
30 
31   @Param({"10", "1000", "1000000"})
32   int size;
33 
34   private static final Object OBJECT = new Object();
35 
builderAdd(int reps)36   @Benchmark int builderAdd(int reps) {
37     int size = this.size;
38     int dummy = 0;
39     for (int rep = 0; rep < reps; rep++) {
40       ImmutableList.Builder<Object> builder = ImmutableList.builder();
41       for (int i = 0; i < size; i++) {
42         builder.add(OBJECT);
43       }
44       dummy += builder.build().size();
45     }
46     return dummy;
47   }
48 
preSizedBuilderAdd(int reps)49   @Benchmark int preSizedBuilderAdd(int reps) {
50     int size = this.size;
51     int dummy = 0;
52     for (int rep = 0; rep < reps; rep++) {
53       ImmutableList.Builder<Object> builder = new ImmutableList.Builder<Object>(size);
54       for (int i = 0; i < size; i++) {
55         builder.add(OBJECT);
56       }
57       dummy += builder.build().size();
58     }
59     return dummy;
60   }
61 
copyArrayList(int reps)62   @Benchmark int copyArrayList(int reps) {
63     int size = this.size;
64     int dummy = 0;
65     for (int rep = 0; rep < reps; rep++) {
66       List<Object> builder = Lists.newArrayList();
67       for (int i = 0; i < size; i++) {
68         builder.add(OBJECT);
69       }
70       dummy += ImmutableList.copyOf(builder).size();
71     }
72     return dummy;
73   }
74 
copyPreSizedArrayList(int reps)75   @Benchmark int copyPreSizedArrayList(int reps) {
76     int size = this.size;
77     int tmp = 0;
78     for (int rep = 0; rep < reps; rep++) {
79       List<Object> builder = Lists.newArrayListWithCapacity(size);
80       for (int i = 0; i < size; i++) {
81         builder.add(OBJECT);
82       }
83       tmp += ImmutableList.copyOf(builder).size();
84     }
85     return tmp;
86   }
87 }
88