I am developing a Web Api application with Asp.Net Core 6.
I see that the IHttpClientFactory CreateClient method creates a new instance of HttpClient every time.
According to this article
Each time we ask for a HttpClient, we get a new instance, which may (or may not) use an existing HttpClientHandler. The HttpClient itself it not too heavy to construct so this is okay.
Do you share this view? Is HttpClient really that light that it doesn't cause performance problems?
If there are actually performance problems, what is the best way to handle them?
CodePudding user response:
A typical web API app has a lot of scoped dependencies that are constructed for each request. Your DbContext
is another of these. It's not too heavy. Allocation and garbage collection are highly optimized for the creation of short-lived objects so that developers don't have to worry about it. The most important optimization of all is minimizing cognitive load.
If there are actually performance problems, the best way to handle them will depend on what caused them, which you'll learn by profiling your running app. But there probably won't be performance problems. And if there are, they probably won't be where you expected. This is true even for experienced developers.
The kind of performance you're worrying about right now is raw CPU and a bit of memory I/O. I'm not sure why new developers fixate on this. The bottleneck for most applications is disk and network I/O.