1 /* 2 * Copyright (C) 2012 Google Inc. 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 examples; 18 19 import com.google.caliper.BeforeExperiment; 20 import com.google.caliper.Benchmark; 21 import com.google.caliper.Param; 22 23 import java.util.ArrayList; 24 import java.util.Iterator; 25 import java.util.LinkedList; 26 import java.util.List; 27 28 /** 29 * Measures performance of list operations. 30 */ 31 public class ListModificationBenchmark { 32 33 private enum Element { 34 INSTANCE, 35 } 36 private enum ListImpl { 37 Array { create()38 @Override List<Element> create() { 39 return new ArrayList<Element>(); 40 } 41 }, 42 Linked { create()43 @Override List<Element> create() { 44 return new LinkedList<Element>(); 45 } 46 }; 47 create()48 abstract List<Element> create(); 49 } 50 51 @Param({"10", "100", "1000", "10000"}) 52 private int size; 53 54 @Param({"Array", "Linked"}) 55 private ListImpl implementation; 56 57 private List<Element> list; 58 setUp()59 @BeforeExperiment void setUp() throws Exception { 60 list = implementation.create(); 61 for (int i = 0; i < size; i++) { 62 list.add(Element.INSTANCE); 63 } 64 } 65 populate(int reps)66 @Benchmark void populate(int reps) throws Exception { 67 for (int rep = 0; rep < reps; rep++) { 68 List<Element> list = implementation.create(); 69 for (int i = 0; i < size; i++) { 70 list.add(Element.INSTANCE); 71 } 72 } 73 } 74 iteration(int reps)75 @Benchmark void iteration(int reps) { 76 for (int rep = 0; rep < reps; rep++) { 77 Iterator<Element> iterator = list.iterator(); 78 while (iterator.hasNext()) { 79 iterator.next(); 80 } 81 } 82 } 83 headAddRemove(int reps)84 @Benchmark void headAddRemove(int reps) { 85 for (int rep = 0; rep < reps; rep++) { 86 list.add(0, Element.INSTANCE); 87 list.remove(0); 88 } 89 } 90 middleAddRemove(int reps)91 @Benchmark void middleAddRemove(int reps) { 92 int index = size / 2; 93 for (int rep = 0; rep < reps; rep++) { 94 list.add(index, Element.INSTANCE); 95 list.remove(index); 96 } 97 } 98 tailAddRemove(int reps)99 @Benchmark void tailAddRemove(int reps) { 100 int index = size - 1; 101 for (int rep = 0; rep < reps; rep++) { 102 list.add(Element.INSTANCE); 103 list.remove(index); 104 } 105 } 106 } 107