blob: 07ae8eb027df376caae9409a01e0c588aef25879 [file] [log] [blame]
Paul Duffin7fc0b452015-11-10 17:45:15 +00001/*
2 * Copyright (C) 2009 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
17package examples;
18
Paul Duffine2363012015-11-30 16:20:41 +000019import com.google.caliper.BeforeExperiment;
20import com.google.caliper.Benchmark;
Paul Duffin7fc0b452015-11-10 17:45:15 +000021import com.google.caliper.Param;
Paul Duffine2363012015-11-30 16:20:41 +000022
Paul Duffin7fc0b452015-11-10 17:45:15 +000023import java.util.AbstractList;
24import java.util.List;
25
26/**
27 * Measures iterating through list elements.
28 */
Paul Duffine2363012015-11-30 16:20:41 +000029public class ListIterationBenchmark {
Paul Duffin7fc0b452015-11-10 17:45:15 +000030
31 @Param({"0", "10", "100", "1000"})
32 private int length;
33
34 private List<Object> list;
35 private Object[] array;
36
Paul Duffine2363012015-11-30 16:20:41 +000037 @BeforeExperiment void setUp() {
Paul Duffin7fc0b452015-11-10 17:45:15 +000038 array = new Object[length];
39 for (int i = 0; i < length; i++) {
40 array[i] = new Object();
41 }
42
43 list = new AbstractList<Object>() {
44 @Override public int size() {
45 return length;
46 }
47
48 @Override public Object get(int i) {
49 return array[i];
50 }
51 };
52 }
53
Paul Duffine2363012015-11-30 16:20:41 +000054 @Benchmark int listIteration(int reps) {
55 int dummy = 0;
Paul Duffin7fc0b452015-11-10 17:45:15 +000056 for (int i = 0; i < reps; i++) {
57 for (Object value : list) {
Paul Duffine2363012015-11-30 16:20:41 +000058 dummy |= value.hashCode();
Paul Duffin7fc0b452015-11-10 17:45:15 +000059 }
60 }
Paul Duffine2363012015-11-30 16:20:41 +000061 return dummy;
Paul Duffin7fc0b452015-11-10 17:45:15 +000062 }
63
Paul Duffine2363012015-11-30 16:20:41 +000064 @Benchmark int arrayIteration(int reps) {
65 int dummy = 0;
Paul Duffin7fc0b452015-11-10 17:45:15 +000066 for (int i = 0; i < reps; i++) {
67 for (Object value : array) {
Paul Duffine2363012015-11-30 16:20:41 +000068 dummy |= value.hashCode();
Paul Duffin7fc0b452015-11-10 17:45:15 +000069 }
70 }
Paul Duffine2363012015-11-30 16:20:41 +000071 return dummy;
Paul Duffin7fc0b452015-11-10 17:45:15 +000072 }
73}