Search code examples
c#.netconcurrencystatic-methodsnon-static

Static methods vs non static methods in .Net


I'm workin with an API in .Net Core and recently I had a situation where the business layer was with all static methods. What kinds of problems can this cause?

  • When the API has a request, it's instantiates a new thread, correct? And the static methods will then occupy double the memory?
  • Can there be performance loss? Because there will be more concurrency between threads and, depending on the processor of the machine, this will be critical.
  • The memory will be released when the application dies. That is, ever will occupy an extra part of memory, while the application is running.

Solution

  • For rendering services via an API, you can't declare your methods (actions to be specific) statically; because, the API context or better said the controller has to be initialized (per request) in order to render the service (get the incoming request and write the response back to the http context).

    But if an API is not the case, static method declaration would in fact help you with performance, as it can be called statically and without the need to instantiate an object. However, it is not a good design (neither is it actually bad). What matters is that, you have to analyze the scenario well to determine if you can really take advantage of modularity earned by functional programing rather than an object oriented approach.

    To break it down more technically for you, there is a design pattern commonly known as the Singleton pattern in which an object is created only once during the life cycle of a program, and a single instance is shared with all entities trying to access the type. That said; it is not bad at all, but once again, you have to well analyze the scenario.

    For example: a singleton entity framework context is a bad idea, because the context may get disposed and you would lose all the changes, tracking data, etc. On the other hand, a singleton ADO.Net context is a good idea if you follow the concept of single responsibility for each of your static methods.