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 import java.util.List; 22 23 /** 24 * Benchmark for various ways to create an {@code ImmutableList}. 25 * 26 * @author Louis Wasserman 27 */ 28 public class ImmutableListCreationBenchmark { 29 30 @Param({"10", "1000", "1000000"}) 31 int size; 32 33 private static final Object OBJECT = new Object(); 34 35 @Benchmark builderAdd(int reps)36 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 49 @Benchmark preSizedBuilderAdd(int reps)50 int preSizedBuilderAdd(int reps) { 51 int size = this.size; 52 int dummy = 0; 53 for (int rep = 0; rep < reps; rep++) { 54 ImmutableList.Builder<Object> builder = new ImmutableList.Builder<>(size); 55 for (int i = 0; i < size; i++) { 56 builder.add(OBJECT); 57 } 58 dummy += builder.build().size(); 59 } 60 return dummy; 61 } 62 63 @Benchmark copyArrayList(int reps)64 int copyArrayList(int reps) { 65 int size = this.size; 66 int dummy = 0; 67 for (int rep = 0; rep < reps; rep++) { 68 List<Object> builder = Lists.newArrayList(); 69 for (int i = 0; i < size; i++) { 70 builder.add(OBJECT); 71 } 72 dummy += ImmutableList.copyOf(builder).size(); 73 } 74 return dummy; 75 } 76 77 @Benchmark copyPreSizedArrayList(int reps)78 int copyPreSizedArrayList(int reps) { 79 int size = this.size; 80 int tmp = 0; 81 for (int rep = 0; rep < reps; rep++) { 82 List<Object> builder = Lists.newArrayListWithCapacity(size); 83 for (int i = 0; i < size; i++) { 84 builder.add(OBJECT); 85 } 86 tmp += ImmutableList.copyOf(builder).size(); 87 } 88 return tmp; 89 } 90 } 91