Hi 👋,

I wanted to write this article to tell you that instantiating a HttpClient class is often a costly operation.

If you have a method that does something like:

public class Main {
  static void myMethod() {
    HttpClient client = new HttpClient()
    // do stuff
  }
}

You should refactor it ASAP. Either move the HttpClient into the class and perhaps ensure that the class is a Singleton or retrieve the HttpClient instance using an Object Pool pattern like the HttpClient class from System.Net.Http.

The HttpClient class instance acts as a session to send HTTP requests. An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.

Thanks for reading!

Further reading