C # Performance Optimization

Source: Internet
Author: User

Today, I want to talk to you about the performance optimization of C #. Of course, I will not talk about the basic principles here. It is assumed that you are very proficient, this article is about programs that require several milliseconds. For basic performance optimization, refer to the articles in the garden. For example:

Summary of. NET Performance Optimization Methods

Let's talk about my test environment:

 


 

A typical laptop, the Chinese version of Windows 7,. net Framework version 4.5, VS is now VS11 beta version. I also tested all the following scenarios in an environment such as VS2008 and found that there were no differences, so I used VS11 as the benchmark.
All the test data is compiled as Relase and does not contain PDB. You can double-click it to run it instead of running it in the VS environment. Click Here http://www.bkjia.com/uploadfile/2012/0516/20120516091804678.rar
Download the source code.
To put it bluntly, first test the first point:
 
Is the static method faster than the instance method?
We always hear from various channels that static methods are faster than instance methods, so I 'd like to try it myself. The test method is simple, and the instance method and static method are called cyclically.

/// <Summary>
/// This is a common class that calls the instance method.
/// </Summary>
Public class C1 {
Public void DoLoop (){
For (int I = 0; I <int. MaxValue; I ++ ){
DoIt ();
}
}
 
Private void DoIt (){
}
}
 
/// <Summary>
/// Use static method call.
/// </Summary>
Public static class C2 {
Public static void DoLoop (){
For (int I = 0; I <int. MaxValue; I ++ ){
DoIt ();
}
}
 
Private static void DoIt (){
}
}
The test results are as follows:


 
If the test is performed multiple times, the basic deviation is not large. It can only be said that the static method is a little faster than the instance method. Because the flexibility of the instance method is much greater than that of the static method, you should generally use the instance method.
I also tried to access the instance field and static field in the method and found that there is no difference, so I will not list the Code separately.
 
Avoid instance creation in the Method
The problem to be discussed is a bit difficult to explain. Let's take a look at the internal code of. net. Below is a Collection <T>. Add method:
Public void Add (T item)
{
If (this. items. IsReadOnly)
{
ThrowHelper. ThrowNotSupportedException (ExceptionResource. NotSupported_ReadOnlyCollection );
}
Int count = this. items. Count;
This. InsertItem (count, item );
}
Note the ThrowHelper class. If it is written by ourselves, the throw new NotSupportedException can be completed in one sentence. Why does Microsoft Write this?
Why does SortedList implementation use ThrowHelper instead of throwing directly?
In fact, I also believe in this truth, and just a while ago, a colleague asked me why there was a gap in the test performance between the two sections of almost the same code, as a result, I put the exception thrown out based on this principle, and the result is actually better.
Now, I want to test it again. What I believe is data:
?
Class C1 {
Private Dictionary <int, int> _ dict = new Dictionary <int, int> ();
Public C1 (){
_ Dict. Add (1, 1 );
_ Dict. Add (2, 2 );
}
 
Public void Do1 (){
Object obj = new object ();
For (int I = 0; I <int. maxvalues/100; I ++ ){
GetItOne (1 );
}
}
 
// This method may create instances internally
Private int GetItOne (int key ){
Int value;
If (! _ Dict. TryGetValue (key, out value )){
Throw new ArgumentOutOfRangeException ("key ");
}
Return value;
}
 
Public void Do2 (){
For (int I = 0; I <int. maxvalues/100; I ++ ){
GetItTwo (1 );
}
}
 
// This method moves the code for creating an instance to the external
Private int GetItTwo (int key ){
Int value;
If (! _ Dict. TryGetValue (key, out value )){
ThrowArgumentOutOfRangeException ();
}
Return value;
}
 
Private static void ThrowArgumentOutOfRangeException (){
Throw new ArgumentOutOfRangeException ("key ");
}
}
The test result is:

 
Basically, it will take about 0.06 seconds, but the benefits of such a large loop are not so obvious, but they can be used. This method is quite comfortable, so we suggest you use it.
 
Next I will experiment with the cost of array enumeration, class and structure creation.

 


From Writing life

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.