I work on a team where every little bit of performance on our application is critical. We're working on migrating from Java to spring boot and there are several instances where we'd need a ObjectFactory<?> to handle the dependency injection of required beans.
I wrote a simple test where we create an object 1 million times using new and 1 million times using spring ObjectFactory<?>.get(). I was seeing a huge difference in performance from this where the pure java version took 0.06 seconds and then the spring version took 23+ seconds.
Test Files
main
@SpringBootApplication
public class DemoApplication {
public static List<Employee> employees = new ArrayList<>();
@Autowired
ObjectFactory<Employee> employeeObjectFactory;
public static void main(String[] args) {
startSpringless();
SpringApplication.run(DemoApplication.class, args);
System.out.println(employees.size());
}
@PostConstruct
public void start(){
var startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
var employee = employeeObjectFactory.getObject();
employee.goToWork();
employees.add(employee);
}
double totalTime = System.currentTimeMillis() - startTime;
System.out.println("Spring seconds: " +totalTime/1000);
}
public static void startSpringless(){
var startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
var employee = new Employee(new Car(), new Clothes());
employee.goToWork();
employees.add(employee);
}
double totalTime = System.currentTimeMillis() - startTime;
System.out.println("No Spring seconds: " +totalTime/1000);
}
}
Employee
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Employee {
private final Car car;
private final Clothes clothes;
@Autowired
public Employee(Car car, Clothes clothes) {
this.car = car;
this.clothes = clothes;
}
public void goToWork(){
}
}
Car and Clothes
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Car {
}
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class Clothes {
}
Is there anyway to create prototype beans that is more peformant? Or is my performance test not working how I expect it is?