DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Microbenchmark For Bridge Vs Reflection Vs Direct Access

11.21.2007
| 1892 views |
  • submit to reddit
        
import java.lang.reflect.Method;

public class TimingTest {
	public interface IFoo { public void foo(); }
	public interface PubFoo { public void foo(); }
	public static class Impl implements PubFoo { public void foo(){} }

	static final int COUNT = 10000000;
	public static void main(String[] args) throws Exception {
		Impl impl = new Impl();
		int count;

		startTiming("Bridge (including BCEL)");
		IFoo ifoo = Bridge.expose(impl, IFoo.class);
		stopTiming();
		startTiming("Bridge (BCEL loaded)");
		Bridge.expose(impl, PubFoo.class);
		stopTiming();

		System.out.println(COUNT+" virtual invocations, warm");

		startTiming("Direct");
		for(int i=0; i<COUNT; i++)
			impl.foo();
		stopTiming();

		Method m = impl.getClass().getMethod("foo",new Class[0]);
		startTiming("Reflection");
		for(int i=0; i<COUNT; i++)
			m.invoke(impl);
		stopTiming();

		startTiming("Bridge");
		for(int i=0; i<COUNT; i++)
			ifoo.foo();
		stopTiming();


		System.out.println("1 virtual invocation on "+COUNT+" objects");

		startTiming("Direct");
		for(int i=0; i<COUNT; i++)
			impl.foo();
		stopTiming();

		startTiming("Reflection");
		Method tmpM = null;
		Class[] no_args = new Class[0];
		for(int i=0; i<COUNT; i++) {
			if(tmpM == null || tmpM.getDeclaringClass() != impl.getClass())
				tmpM = impl.getClass().getMethod("foo",no_args);
			tmpM.invoke(impl);
		}
		stopTiming();

		startTiming("Bridge");
		for(int i=0; i<COUNT; i++) {
			IFoo temp = Bridge.expose(impl, IFoo.class);
		}
		stopTiming();

		
		System.out.println(COUNT+" interface invocations, warm");
		PubFoo pfoo = (PubFoo)impl;
		Method mi = impl.getClass().getInterfaces()[0].getMethod("foo", new Class[]{});
		IFoo iifoo = Bridge.expose(impl, PubFoo.class, IFoo.class);

		startTiming("Direct");
		for(int i=0; i<COUNT; i++)
			pfoo.foo();
		stopTiming();

		startTiming("Reflection");
		for(int i=0; i<COUNT; i++)
			mi.invoke(impl);
		stopTiming();

		startTiming("Bridge");
		for(int i=0; i<COUNT; i++)
			iifoo.foo();
		stopTiming();
		
	}
	static long timer;
	static void startTiming(String task) {
		System.out.printf("  * %12s - ", task);
		System.out.flush();
		timer = System.currentTimeMillis();
	}
	static void stopTiming() {
		long time = System.currentTimeMillis() - timer;
		System.out.println(time+" ms");
	}
}