1 /* 2 * Copyright (C) 2023 The Android Open Source Project 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 libcore.benchmark; 18 19 import androidx.benchmark.BenchmarkState; 20 import androidx.benchmark.junit4.BenchmarkRule; 21 import androidx.test.runner.AndroidJUnit4; 22 23 import dalvik.annotation.optimization.NeverInline; 24 25 import org.junit.Rule; 26 import org.junit.runner.RunWith; 27 import org.junit.Test; 28 29 import java.lang.invoke.MethodHandle; 30 import java.lang.invoke.MethodHandles; 31 import java.lang.invoke.MethodType; 32 33 @RunWith(AndroidJUnit4.class) 34 public class MethodHandlesTest { 35 36 @Rule 37 public BenchmarkRule benchmarkRule = new BenchmarkRule(); 38 39 private static final MethodHandle MH_1; 40 private static final MethodHandle MH_0; 41 static { 42 try { 43 MH_1 = MethodHandles.lookup() 44 .findVirtual(A.class, "identity", MethodType.methodType(int.class, int.class)); 45 MH_0 = MethodHandles.lookup() 46 .findVirtual(A.class, "constant", MethodType.methodType(int.class)); 47 } catch (ReflectiveOperationException ex) { 48 throw new RuntimeException(ex); 49 } 50 } 51 52 private final A a = new A(); 53 private int x1 = 10; 54 55 @Test directCall_noArguments()56 public void directCall_noArguments() { 57 final BenchmarkState state = benchmarkRule.getState(); 58 while (state.keepRunning()) { 59 a.constant(); 60 } 61 } 62 63 @Test directCall_singleArgument()64 public void directCall_singleArgument() { 65 final BenchmarkState state = benchmarkRule.getState(); 66 while (state.keepRunning()) { 67 a.identity(x1); 68 } 69 } 70 71 @Test methodHandles_noArguments()72 public void methodHandles_noArguments() throws Throwable { 73 final BenchmarkState state = benchmarkRule.getState(); 74 while (state.keepRunning()) { 75 MH_0.invoke(a); 76 } 77 } 78 79 @Test methodHandles_singleArgument()80 public void methodHandles_singleArgument() throws Throwable { 81 final BenchmarkState state = benchmarkRule.getState(); 82 while (state.keepRunning()) { 83 MH_1.invoke(a, x1); 84 } 85 } 86 87 static class A { 88 89 @NeverInline constant()90 public int constant() { 91 return 42; 92 } 93 94 @NeverInline identity(int a)95 public int identity(int a) { 96 return a; 97 } 98 99 } 100 101 } 102