FieldAccessBenchmark.java revision 5a7833b406bb2716b057d3ed923f22f1f86b2a20
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 17package benchmarks; 18 19import com.google.caliper.Param; 20import com.google.caliper.Runner; 21import com.google.caliper.SimpleBenchmark; 22 23/** 24 * What does field access cost? 25 */ 26public class FieldAccessBenchmark extends SimpleBenchmark { 27 private static class Inner { 28 public int publicInnerIntVal; 29 protected int protectedInnerIntVal; 30 private int privateInnerIntVal; 31 int packageInnerIntVal; 32 } 33 int intVal = 42; 34 final int finalIntVal = 42; 35 static int staticIntVal = 42; 36 static final int staticFinalIntVal = 42; 37 public int timeField(int reps) { 38 int result = 0; 39 for (int rep = 0; rep < reps; ++rep) { 40 result = intVal; 41 } 42 return result; 43 } 44 public int timeFieldFinal(int reps) { 45 int result = 0; 46 for (int rep = 0; rep < reps; ++rep) { 47 result = finalIntVal; 48 } 49 return result; 50 } 51 public int timeFieldStatic(int reps) { 52 int result = 0; 53 for (int rep = 0; rep < reps; ++rep) { 54 result = staticIntVal; 55 } 56 return result; 57 } 58 public int timeFieldStaticFinal(int reps) { 59 int result = 0; 60 for (int rep = 0; rep < reps; ++rep) { 61 result = staticFinalIntVal; 62 } 63 return result; 64 } 65 public int timeFieldCached(int reps) { 66 int result = 0; 67 int cachedIntVal = this.intVal; 68 for (int rep = 0; rep < reps; ++rep) { 69 result = cachedIntVal; 70 } 71 return result; 72 } 73 public int timeFieldPrivateInnerClassPublicField(int reps) { 74 int result = 0; 75 Inner inner = new Inner(); 76 for (int rep = 0; rep < reps; ++rep) { 77 result = inner.publicInnerIntVal; 78 } 79 return result; 80 } 81 public int timeFieldPrivateInnerClassProtectedField(int reps) { 82 int result = 0; 83 Inner inner = new Inner(); 84 for (int rep = 0; rep < reps; ++rep) { 85 result = inner.protectedInnerIntVal; 86 } 87 return result; 88 } 89 public int timeFieldPrivateInnerClassPrivateField(int reps) { 90 int result = 0; 91 Inner inner = new Inner(); 92 for (int rep = 0; rep < reps; ++rep) { 93 result = inner.privateInnerIntVal; 94 } 95 return result; 96 } 97 public int timeFieldPrivateInnerClassPackageField(int reps) { 98 int result = 0; 99 Inner inner = new Inner(); 100 for (int rep = 0; rep < reps; ++rep) { 101 result = inner.packageInnerIntVal; 102 } 103 return result; 104 } 105} 106