Skip to content

Instantly share code, notes, and snippets.

@gissuebot
Created July 7, 2014 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gissuebot/0074e6a0e243b9d997f4 to your computer and use it in GitHub Desktop.
Save gissuebot/0074e6a0e243b9d997f4 to your computer and use it in GitHub Desktop.
Migrated attachment for Guice issue 435, comment 9
package com.google.inject.assistedinject;
import java.util.concurrent.TimeUnit;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.InjectorBuilder;
import com.google.inject.Provider;
import junit.framework.TestCase;
public class AssistedInjectPerfTest extends TestCase {
public void testTimeForFactoryProvider1() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Bar.class);
bind(FooFactory.class).toProvider(FactoryProvider.newFactory(FooFactory.class, OldFoo.class));
}
});
speedTest("Factory Provider 1", injector.getProvider(FooFactory.class));
}
public void testTimeForFactoryProvider2() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Bar.class);
bind(FooFactory.class).toProvider(FactoryProvider.newFactory(FooFactory.class, NewFoo.class));
}
});
speedTest("Factory Provider 2", injector.getProvider(FooFactory.class));
}
public void testTimeForFactoryProviderRequireExplicit() {
Injector injector = new InjectorBuilder()
.requireExplicitBindings()
.addModules(new AbstractModule() {
@Override
protected void configure() {
bind(Bar.class);
bind(FooFactory.class).toProvider(FactoryProvider.newFactory(FooFactory.class, NewFoo.class));
}
}).build();
speedTest("Factory Provider 2 - Explicit Bindings Required", injector.getProvider(FooFactory.class));
}
private void speedTest(String name, Provider<FooFactory> factory) {
//warmup.
for(int i = 0; i < 1000; i++) {
factory.get().create("a");
}
//test.
long start = System.nanoTime();
for(int i = 0; i < 100000; i++) {
factory.get().create("a");
}
long end = System.nanoTime();
System.out.println("Test for <" + name + "> -- " + TimeUnit.NANOSECONDS.toMillis(end - start));
}
private static interface Foo {}
private static interface FooFactory { Foo create(String string); }
private static class Bar {}
private static class NewFoo implements Foo {
@SuppressWarnings("unused") @Inject NewFoo(Bar bar, @Assisted String string) {}
}
private static class OldFoo implements Foo {
@SuppressWarnings({ "unused", "deprecation" }) @AssistedInject OldFoo(Bar bar, @Assisted String string) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment