JAX-RS and performance of per-request vs singleton resource classes

Per default JAX-RS instantiates your resource classes per request but you have also the possibility to create only one instance for the whole application lifecycle. There was a question on stackoverflow which approach is better in terms of performance. As I also did not know I set up a simple load test quite similar to this dependency injection performance test.

The test includes 4 resource classes: 2 per-request scoped and 2 singletons. Two are just returning a query param. In the other two resources I injected the UriInfo via @Context. The context is specific to a particular request. So on a request-scoped resource it can be injected at creation time. For a singleton resource this needs to be handled different by maybe creating proxy objects.

The tests are using RESTeasy 3.0.10.Final on Wildfly 8.2.0.Final. Each test was executed with 5 threads and repeated 500000 times.

These are the results:

As we can see the difference between the tests is around 1.5 % so I’m pretty sure: If your application has a performance problem it’s caused by anything but the lifecycle of your resource classes.

Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.

You can find the sources of this test on Github.