When I using spring framework to write business code, I always use the singleton scope and avoid using the prototype scope. I think there is a performance difference between prototype and singleton. Because of the prototype scope, spring creates a new instance every call. And I think it is slower than using the singleton scope. Am I right? And am I giving too many considerations to the performance?
I can relate to the question, I have been researching it recently. Construction of objects is very cheap, unless they actually do some heavy lifting in the constructor. You never think twice about constructing a bunch of lambdas in one statement. That's not the problem.
The problem is Spring's inefficiency, the way it wasn't architectured right. I have recently benchmarked Spring vs Guice. Singletons are slightly faster with Spring, but Prototypes are 20 times slower.
From code sanity point of view, you should always prefer Prototypes. Guice defaults to prototypes. javax.inject.Inject documentation defaults to prototypes. Spring lists some vague historical reasons and does Singletons.
Prototypes are safer because they cannot accidentally store state and use it in the wrong context. They cannot store "userId" from one request and use it in another, since with Prototypes, a brand new instance with clean state gets created every time. That's how I learned this pattern: we cached the wrong user context accidentally when using Singletons with RequestScoped Providers. Ouch. That mistake is important to avoid. Getting CPU is a much smaller problem.
To summarize: use Prototypes for better code, and dont use Spring if performance is very important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With