blob: bdc255b9a96d506b4f91b7489fde42d3d32a170e [file] [log] [blame]
Elliott Hughes97aba272013-02-13 16:21:51 -08001/*
2 * Copyright (C) 2010 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 benchmarks;
18
19import com.google.caliper.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22
23/**
24 * How do various ways of iterating through an array compare?
25 */
26public class ArrayIterationBenchmark extends SimpleBenchmark {
27 Foo[] mArray = new Foo[27];
28 {
29 for (int i = 0; i < mArray.length; ++i) mArray[i] = new Foo();
30 }
31 public void timeArrayIteration(int reps) {
32 for (int rep = 0; rep < reps; ++rep) {
33 int sum = 0;
34 for (int i = 0; i < mArray.length; i++) {
35 sum += mArray[i].mSplat;
36 }
37 }
38 }
39 public void timeArrayIterationCached(int reps) {
40 for (int rep = 0; rep < reps; ++rep) {
41 int sum = 0;
42 Foo[] localArray = mArray;
43 int len = localArray.length;
44
45 for (int i = 0; i < len; i++) {
46 sum += localArray[i].mSplat;
47 }
48 }
49 }
50 public void timeArrayIterationForEach(int reps) {
51 for (int rep = 0; rep < reps; ++rep) {
52 int sum = 0;
53 for (Foo a: mArray) {
54 sum += a.mSplat;
55 }
56 }
57 }
58}