


Implementation of C# singleton pattern and examples of performance comparison
This article mainly introduces relevant information about the implementation and performance comparison of C# singleton mode. It introduces 6 implementation methods in detail. Friends in need can refer to the following
Introduction
A singleton refers to a class that can only have one instance (in C#, more accurately, it is a class that can only have one instance in each AppDomain. It is used in software engineering One of the most common modes. After the first user creates an instance of this class, subsequent users who need to use this class can only use the previously created instance and cannot create a new instance. A singleton is created when it is used for the first time. This article will introduce several singleton implementation methods in C# and analyze the thread safety and performance differences between them. There are many, but from the simplest implementation (non-lazy-loading, non-thread-safe, and inefficient) to a lazily-loadable, thread-safe, and efficient implementation, they all have some basic things in common:
- Singleton classes have only one private parameterless constructor
- The class is declared sealed (not required)
- There is a static variable in the class that holds a reference to the created instance
- The singleton class will provide a static method or property to return a reference to the created instance (eg.GetInstance)
One non-thread safety
//Bad code! Do not use!
public sealed class Singleton
{
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
This method is not thread-safe Yes, there will be two threads executing if (instance == null) at the same time and creating two different instances. The one created later will replace the newly created one, causing the previously obtained reference to be empty
#. ##Second Simple Thread Safety Implementation
public sealed class Singleton { private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } } }Compared with implementation one, this version adds a lock on the instance. The padlock must be locked before calling the instance, thus avoiding Due to the thread conflict in Implementation 1, this implementation will only create one instance from beginning to end. However, since the lock is used every time the instance is called, and the cost of calling the lock is large, this implementation will have a certain performance loss #. ## Note that here we use a new private object instance padlock to implement the lock operation, instead of directly locking the Singleton. There are potential risks in directly locking the type, because this type is public, so in theory. It will be called in any code, and locking it directly will cause performance problems and even deadlocks.
Note: In C#, the same thread can lock an object multiple times. , but if different threads are locked at the same time, thread waiting may occur, or serious deadlock may occur. Therefore, when we use lock, try to lock private variables in the class, so as to avoid the above situation.
Triple double verification thread safety implementationpublic sealed calss Singleton { private static Singleton instance = null; private static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (padlock) { if (instance == null) { instance = new Singleton(); } } } return instance; } } }
While ensuring thread safety, this implementation also avoids the lock operation every time Instance is called, which will save money A certain amount of time. However, this implementation also has its disadvantages:
1 does not work in Java. (The specific reasons can be found in the original text, I don’t understand much here)
2 Programmers can easily make mistakes when implementing it themselves. If you make your own modifications to the code in this mode, be very careful because the logic of double check is relatively complex and it is easy to make mistakes due to poor thinking.Four thread-safe implementations without locks
public sealed class Singleton { //在Singleton第一次被调用时会执行instance的初始化 private static readonly Singleton instance = new Singleton(); //Explicit static consturctor to tell C# compiler //not to mark type as beforefieldinit static Singleton() { } private Singleton() { } public static Singleton Instance { get { return instance; } } }
This implementation is very simple and does not use locks, but it is still thread-safe. A static, readonly Singleton instance is used here. It will create a new instance when the Singleton is called for the first time. The thread safety guarantee when creating the new instance is directly controlled by .NET. We can think of it as an atomic operation. And it will only be created once in an AppDomaing.
This implementation also has some shortcomings:1The timing of instance being created is unknown, and any call to Singleton will create the instance in advance2The cyclic call of the static constructor . If there are two classes, A and B, and B is called in the static constructor of A, and A is called in the static constructor of B, these two will form a circular call, which will seriously cause the program to crash. 3 We need to manually add the static constructor of Singleton to ensure that the Singleton type will not be automatically added with the beforefieldinit Attribute to ensure that the instance will be created when Singleton is called for the first time.
4 The readonly attribute cannot be changed at runtime. If we need to dispose the instance and recreate a new instance when the program is running, this implementation method cannot be satisfied.
Five fully lazy loading implementation (fully lazy instantiation)
public sealed class Singleton { private Singleton() { } public static Singleton Instance { get { return Nested.instance; } } private class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }
Implementation five is a wrapper for implementation four. It ensures that instance will only be called in the get method of Instance and will only be initialized before the first call. It is a version of implementation 4 that ensures lazy loading.
6 Use .NET4's Lazypublic sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { } }
.NET4 or above version supports Lazy Performance difference In the previous implementation, we emphasized the thread safety and lazy loading of the code. However, in actual use, if the initialization of your singleton class is not a time-consuming operation or the initialization sequence does not cause bugs, delayed initialization is a dispensable feature because the time taken by the initialization is negligible. of. In actual usage scenarios, if your singleton instance will be called frequently (such as in a loop), then the performance consumption caused by ensuring thread safety is more worthy of attention. In order to compare the performance of these implementations, I did a small test, looping through the singletons in these implementations 900 million times, calling the instance method each time to perform a count++ operation, and every one million Output once, the running environment is Visual Studio for Mac on MBP. The results are as follows: The test method is not rigorous, but it can still be seen that method two has The need to call lock is the most time-consuming, almost three times as long as the others. Ranked second is the implementation using the .NET Lazy type, which is about one-half more than the others. The remaining four have no obvious differences. Summary Generally speaking, the various singleton implementation methods mentioned above are not very different under today's computer performance, unless you need a particularly large amount of concurrency. Only when you call instance will you need to consider lock performance issues. For ordinary developers, it is good enough to use method 2 or method 6 to implement singletons. Methods 4 and 5 require a good understanding of the C# running process and implementation They require certain skills, and the time they save is still limited. Quote Most of this article is translated from Implementing the Singleton Pattern in C#, with some of my own understanding added. This is what I saw when I searched for static readonly field initializer vs static constructor initialization. I would like to express my thanks to the two authors here.
Thread safety
Lazy loading
Test running time (ms)
Realize one
No
Yes
15532
Realization Two
Yes
Yes
45803
Realization Three
Yes is
15953
realizes four
is
incomplete
14572
realize five
是
是
14295
realize six
是
是
22875
The above is the detailed content of Implementation of C# singleton pattern and examples of performance comparison. For more information, please follow other related articles on the PHP Chinese website!

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.