Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility/Helper stateless static class vs stateless non-static class

Tags:

c#

.net

Is there any difference between creating a stateless static utility class versus stateless non-static utility class from memory allocation point of view? Per my understanding, static class may actually be better as no object will be allocated on GC Heap. Only method table will be created on High Frequency heap whereas for non-static class, an object will be created on GC Heap alongwith Method table on HF heap. Need help from you guys to confirm it and please tell me if I am missing any other considerations.

like image 246
jags Avatar asked Aug 15 '12 18:08

jags


1 Answers

Yes. If the methods are all static, then no instances are going to be on the managed heap. Every time you call, you will reference the type directly and access it's members without allocating memory on the heap.

If you have an instance class, then every time you create an instance, you would incur a cost on the heap. If you're also not holding on to a reference, then you're going to have a high churn in generation 0 of the CLR. This assumes you will be creating a great deal of objects to make these calls.

Of course, if you are implementing the singleton pattern then the cost will be small, as you're only going to implement a single instance of your object.

However, this is all moot, as it's a micro optimization; unless you find yourself creating an exorbitant amount of these objects to perform this function and through profiling it's determined that you actually have a problem, then it should be a matter of whatever is easiest to maintain.

I will say though, that if a method is stateless and it naturally looks like it would operate off an existing type then I will typically write an extension method; it's a static call, but gives the appearance of an instance call, which to some (and me personally) has a much nicer flow in code than calling a static method directly off the type (especially when it enables me to design a fluent interface).

like image 199
casperOne Avatar answered Oct 16 '22 11:10

casperOne