Home > Net >  Does dependency injection in ASP.NET Core add performance overhead?
Does dependency injection in ASP.NET Core add performance overhead?

Time:10-28

I'm working on a app where DI was avoided to improve performance. The service dependency is implemented as a static class and referenced directly in the calling class. This is presenting the typical challenges for testing since it's not possible in inject a stub for this service.

My first thought is to setup a regular class and interface, put it into the container as a singleton, and then inject it into the calling class constructor. This API app is very performance critical, so the design choices cannot add any extra milliseconds to the response time.

Is it possible to use DI without adding some performance overhead? If not, is there another design pattern I can use to maintain performance but improve the testability of the class at the same time?

CodePudding user response:

I ran a simple test to verify this and found that using a Singleton service from DI did not add any significant overhead to the performance.

I created a simple service with an interface and registered it in the services collection. I created 2 controllers. In one I used new Service() to get the instance and in the other I injected it through in constructor.

I started the app in Release build mode and ran load tests on each controller using K6. The controller that uses new Service() averaged 184.94 microseconds and the one that used injection averaged 186.07 microseconds.

So using DI did add a slight (1 millionth of a second) overhead. That may be small enough to be unnoticeable in using the API.

  • Related