Sitemap

Performance of Static vs Singleton

2 min readMay 15, 2021

We will discuss the use of Static class vs of Singleton object.

Press enter or click to view image in full size

Introduction

As we know static classes are used directly without creating any object of that class and a singleton is a design pattern that uses a single object to be created which is used during the lifetime of the program. But there is a lot of debate around the use of static vs singleton.

Below are some differences between using one over the other.

  • With a singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.
  • Singleton object can be passed to methods while static class as it does not have instance can’t be passed as parameters.
  • Singleton can be inherited which supports open/close principles in SOLID principles on the other hand static class can’t be inherited and we need to make changes in itself.
  • Singleton objects are stored in Heap, but static objects are stored in the stack.
  • If your need to maintain a state then a singleton pattern is a better choice than static class, because maintaining state in static class leads to bugs, especially in a concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.
  • Singleton class can be lazy-loaded if it's a heavy object, but the static class doesn’t have such advantages and always eagerly loaded.

Singleton vs Static code snippet

https://gist.github.com/chirantar/e5e4ab4cdf22700dd6b39e3a5cc38340

Now we can talk about Performance

Static classes are loaded early at the start of a program, resulting in classloader issues as the program needs more memory at the beginning. Singleton object comes in handy as this object comes into existence after a program needs to access that class method, so it means we can defer the object creation of singleton until needed.

Also, we can see that static classes are loaded into stack memory and it remains till the end of the program and while the singleton object lives inside the heap as it created dynamically at run time.

Then comes another point of maintaining a state inside the static class is difficult especially in a concurrent environment which actually leads to race conditions without adequate synchronization parallel modification by multiple threads.

Conclusion

As singleton is more effective we should carefully use static where we need.

Thank you for reading.

If you find this article useful, you know what to do now. Hit that clap button and follow me to get more articles on your feed.

You can follow me on Twitter.

https://twitter.com/Chirantar

--

--

No responses yet