Comparison of two methods of C # implementing Singleton

Source: Internet
Author: User
Tags comparison count datetime execution implement tostring volatile
Comparison Singleton design mode creates a unique global object in the application, that is, the object can only be instantiated once. The window manager in the application, or the database connection pool, is a typical application of the singleton pattern.

The use of C # language can be easily implemented Singleton mode, however, the same is the implementation of Singleton mode, due to the different ways of implementation, the operating effect will be different. The following are two ways to illustrate and compare C # to implement the Singleton pattern:

C # unique way to implement Singleton (mode 1)



/**////<summary>
A simple way to implement a single key mode
</summary>
public sealed class SampleSingleton1
{
private int m_counter = 0;

Private SampleSingleton1 ()
{
Console.WriteLine ("Initialize SampleSingleton1. ");
}

public static readonly SampleSingleton1 Singleton = new SampleSingleton1 ();

/**////<summary>
Call Count counter
</summary>
public void Counter ()
{
M_counter + +;
}
}
To illustrate, the sealed keyword guarantees that the single key class is not inherited, and the ReadOnly keyword guarantees that the singleton instance entry is read-only.

Traditional way to implement Singleton (mode 2)

This is called the traditional way because C + + and Java are in this way, the code is as follows:

/**////<summary>
The traditional implementation mode of single-key mode
</summary>
public class SampleSingleton2
{
Note: It is best to use the volatile keyword for public variables, for reasons such as MSDN
private static volatile SampleSingleton2 m_instance = null;

private int m_counter = 0;

Private SampleSingleton2 ()
{
Console.WriteLine ("Initialize SampleSingleton2. ");
}

/**////<summary>
Get single Key instance
</summary>
public static SampleSingleton2 Singleton
{
Get
{
if (m_instance = null)
{
Lock (typeof (SampleSingleton2))
{
if (m_instance = null)
{
M_instance = new SampleSingleton2 ();
}
}
}

return m_instance;
}
}

/**////<summary>
Call Count counter
</summary>
public void Counter ()
{
M_counter + +;
}
}

The code above uses the volatile keyword and the lock keyword to ensure that it is created correctly (that is, only once) and that the instance is obtained correctly.

Compare two ways of implementing

It can be seen that the way 1 of the code less a lot, also did not carry out mutual exclusion judgment and locking operation, so the speed also has a certain advantage. But can not say Method 1 is certainly better than Method 2, although the method 1 code less and faster, but Method 1 initialization action is at the start of the entire program, and Method 2 initialization action is the first call to do. Therefore, in the specific application should be based on the actual situation requirements to choose the way to achieve.

The following is a separate test code for the two implementations:



Class APP
{
/**////<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
DateTime Milestone;
int maxcalltimes = 100000000;

The first call to SampleSingleton1 's counter method
Console.WriteLine ("First call the counter method of SampleSingleton1");
SampleSingleton1.Singleton.Counter ();

Calculate the time spent on 10,000 calls
Milestone = DateTime.Now;
for (int i = 0; i < maxcalltimes i + +)
{
SampleSingleton1.Singleton.Counter ();
}
Console.WriteLine (maxcalltimes.tostring () + "Second Call execution time is:" + (TimeSpan) (Datetime.now-milestone). Totalmilliseconds.tostring ());
Console.WriteLine ("");


The first call to SampleSingleton2 's counter method
Console.WriteLine ("First call the counter method of SampleSingleton2");
SampleSingleton2.Singleton.Counter ();

Calculate the time spent on 10,000 calls
Milestone = DateTime.Now;
for (int i = 0; i < maxcalltimes i + +)
{
SampleSingleton2.Singleton.Counter ();
}
Console.WriteLine (maxcalltimes.tostring () + "Second Call execution time is:" + (TimeSpan) (Datetime.now-milestone). Totalmilliseconds.tostring ());

String str = Console.ReadLine ();
}
}
The results of the operation are as follows:


Initialize SampleSingleton1.
The first call to SampleSingleton1 's counter method
100 million Call execution time is: 1722.4768

The first call to SampleSingleton2 's counter method
Initialize SampleSingleton2.
100 million Call execution time is: 3805.472

As can be seen from the results of the operation, the initialization of method 1 occurs when the application is initialized, and the initialization of Method 2 occurs on the first call. The execution time is in milliseconds, and the efficiency of Method 1 is about 1 time times higher than the efficiency of Method 2.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.