Home | History | Annotate | Download | only in benchmarks
      1 /*
      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 
     17 package benchmarks;
     18 
     19 /**
     20  * How do various ways of iterating through an array compare?
     21  */
     22 public class ArrayIterationBenchmark {
     23     Foo[] mArray = new Foo[27];
     24     {
     25         for (int i = 0; i < mArray.length; ++i) mArray[i] = new Foo();
     26     }
     27     public void timeArrayIteration(int reps) {
     28         for (int rep = 0; rep < reps; ++rep) {
     29             int sum = 0;
     30             for (int i = 0; i < mArray.length; i++) {
     31                 sum += mArray[i].mSplat;
     32             }
     33         }
     34     }
     35     public void timeArrayIterationCached(int reps) {
     36         for (int rep = 0; rep < reps; ++rep) {
     37             int sum = 0;
     38             Foo[] localArray = mArray;
     39             int len = localArray.length;
     40 
     41             for (int i = 0; i < len; i++) {
     42                 sum += localArray[i].mSplat;
     43             }
     44         }
     45     }
     46     public void timeArrayIterationForEach(int reps) {
     47         for (int rep = 0; rep < reps; ++rep) {
     48             int sum = 0;
     49             for (Foo a: mArray) {
     50                 sum += a.mSplat;
     51             }
     52         }
     53     }
     54 }
     55