Timone maximizes. NET performance and provides interesting responses.

Source: Internet
Author: User

 

Optimize. Net Performance

1) Avoid using arraylist.
Because any object to be added to the arraylist must be of the system. Object type. When retrieving data from the arraylist, it must be split back to the actual type. We recommend that you replace arraylist with a custom set type .. NET 2.0 provides a new type called generic, which is a strong type. Using a generic set can avoid binning and unboxing and improve performance.

2) use hashtale to replace other dictionary Collection types (such as stringdictionary, namevaluecollection, and hybridcollection). You can use hashtable to store a small amount of data.

3) Declare constants for string containers. Do not enclose the characters in double quotation marks.
// Avoid
//
Myobject OBJ = new myobject ();
OBJ. Status = "active ";

// Recommended
Const string c_status = "active ";
Myobject OBJ = new myobject ();
OBJ. Status = c_status;

4) do not use uppercase or lowercase to convert strings and use string. Compare instead. It can be case-insensitive for comparison.

Example:
 
Const string c_value = "Compare ";
If (string. Compare (svariable, c_value, true) = 0)
{
Console. Write ("same ");
}

5) Use stringbuilder instead of the string connector "+ ",.

// Avoid
String sxml = "<parent> ";
Sxml + = "<child> ";
Sxml + = "data ";
Sxml + = "</child> ";
Sxml + = "</parent> ";

// Recommended
Stringbuilder sbxml = new stringbuilder ();
Sbxml. append ("<parent> ");
SbXML. Append ("<child> ");
SbXML. Append ("Data ");
SbXML. Append ("</child> ");
SbXML. Append ("</parent> ");

6) If you are only reading from the XML object, avoid using XMLDocumentt, instead use XPathDocument, which is readonly and so improves performance.
If you only read data from an XML Object and use the read-only XPathDocument instead of XMLDocument, the performance can be improved.
// Avoid
XmlDocument xmld = new XmlDocument ();
Xmld. LoadXml (sXML );
TxtName. Text = xmld. SelectSingleNode ("/packet/child"). InnerText;

.

// Recommended
XPathDocument xmldContext = new XPathDocument (new StringReader (oContext. Value ));
XPathNavigator xnav = xmldContext. CreateNavigator ();
XPathNodeIterator xpNodeIter = xnav. Select ("packet/child ");
ICount = xpNodeIter. Count;
XpNodeIter = xnav. SelectDescendants (XPathNodeType. Element, false );
While (xpNodeIter. MoveNext ())
{
SCurrValues + = xpNodeIter. Current. Value + "~ ";
}

7) avoid declaring variables in the cyclic body. Declare variables in the circulating body and initialize them in the cyclic body.

// Avoid
For (int I = 0; I <10; I ++)
{
SomeClass objSC = new SomeClass ();
.
.
.

}

// Recommended
SomeClass objSC = null;
For (int I = 0; I <10; I ++)
{
ObjSC = new SomeClass ();

.
.
.
}

8) catch the specified Exception. Do not use general System. Exception.

// Avoid
Try
{
<Some logic>
}
Catch (Exception exc)
{
<Error handling>
}

// Recommended
Try
{
<Some logic>
}
Catch (System. NullReferenceException exc)
{
<Error handling>
}
Catch (System. ArgumentOutOfRangeException exc)
{
<Error handling>
}
Catch (System. InvalidCastException exc)
{
<Error handling>
}

9) When Try... catch... finally is used, the occupied resources such as connections and file streams should be released in finally.
Otherwise, the resources occupied after an error is caught cannot be released.

Try
{
...
}
Catch
{...}
Finally
{
Conntion. close ()
}
10) Avoid using recursive calls and nested loops. Using them will seriously affect performance and will be used only when you have to use them.

11) Use appropriate Caching policies to improve performance
Now, I will write it here today. I will try again later.

Although I don't know where you copied it, I still want to tell you that most of the content in your article is not rigorous, or even incorrect:
1) Avoid using arraylist.
Not rigorous. Performance Loss exists only when the element type is value type.

2) use HashTale to replace other dictionary Collection types (such as StringDictionary, NameValueCollection, and HybridCollection). You can use HashTable to store a small amount of data.
Error. No HashTable, only Hashtable. The argument is also incorrect, which is the opposite of "1st.

3) Declare constants for string containers. Do not enclose the characters in double quotation marks.
Not rigorous. Although defining string constants is a good coding habit, it has nothing to do with performance. The compiler usually performs well for us.

4) do not use UpperCase or Lowercase to convert strings and use String. Compare instead. It can be case-insensitive for comparison.
It is basically correct. The reason is basic. 1. This is because this writing method has very limited performance improvement, and excellent programmers often have such excellent habits. As a principle for improving performance, it is simply a masterpiece.

5) Use StringBuilder instead of the string connector "+ ",.
Not rigorous. If only two string items are merged, "+" provides better performance.

6) If you only want to read data from an XML object, replace XMLDocument with a read-only XPathDocument to improve the performance.
Not rigorous. The concept of "reading data" is unclear. Whether XPathDocument or XmlDocument is used is selected based on the "function" instead of "performance.

7) avoid declaring variables in the cyclic body. Declare variables in the circulating body and initialize them in the cyclic body.
Error. There is no performance problem here. It can be said that it is better to declare in a loop body. The variable has a smaller scope. There is no garbage collection problem here, because the stack space is used.

8) catch the specified Exception. Do not use general System. Exception.
Not rigorous. This does not involve performance, but makes the program readable.

9) When Try... catch... finally is used, the occupied resources such as connections and file streams should be released in finally.
Not rigorous. This does not involve performance issues, but leaks.

10) Avoid using recursive calls and nested loops. Using them will seriously affect performance and will be used only when you have to use them.
Error. Insufficient reasons. Recursion often makes the logic simple and makes the system more stable. Of course, too deep recursion will increase the stack space boundary check and allocate larger stack space overhead. But the impact is subtle.

11) Use appropriate Caching policies to improve performance
Correct, but not nonsense. I don't need to say anything.

On the contrary, I agree with hal, NoMagic, and awu statements.
I am very disappointed that such an article has reached the top of Dflying Chen. Pisces comment on

Haha, it seems that performance optimization is just important to select the most appropriate method at the most appropriate time.

How to maximize. NET performance (continued)

Yesterday I posted an article on how to maximize the performance. many people commented on the NET Performance articles. I would like to thank you for your comments here. Some of them indicate some mistakes in the articles. Here I would like to thank those who wrote the comments patiently, the younger brother has benefited a lot.

Yesterday, the article mainly improved the speed from writing code details. It may be difficult to actually feel the performance improvement, but as a programmer, continuously improving the quality of your code is a constant goal.

In fact, with the development of hardware, the speed of hardware is now far enough to meet the needs of most people, and some people even propose algorithms that are increasingly ineffective in software development. I remember seeing the data structure video in Massachusetts before, and the professor in the lecture asked a question (I don't remember clearly, but he probably meant this): Since algorithms have become unimportant now, why should we study it here? The answer he gave is "SPEED". We are pursuing SPEED just like a racing driver!

At present, many systems do not place the development speed first. Others, such as stability, security, and reusability, are usually the most important. Currently, the design mode and development architecture are not mainly used to solve performance problems. All of the above are considered by analysts and architects. For example, some of our small programmers can only optimize the program in a small place of code, a class, a method, and a line of code. I think it is good to pay more attention to some details.

Well, I 've talked a lot of nonsense about today's theme. Now, many of the performance overhead of the network systems developed mainly involve data reading, transmission, and faster reading speed, our goal is to use less network bandwidth. I will talk about how to improve. net performance in this regard.

1. Paging data at the data layer. It can be implemented through ExcuteReader or stored procedure. There are many methods, so I will not talk much about it. (You can refer to what I wrote)

2. use ExcuteReader as much as possible to read data. ExcuteReader is the most efficient, and ExcuteReader is used for all data access in PetShop 4.0 of MicroSoft, unless you have special requirements for non-connection (such as SmartClient ).

3. In non-connection scenarios, DataTable is better than DataSet, unless you want to save multiple Relational Tables.

4. Use the ImportRow method of DataTable.
In some cases, a large amount of data needs to be copied from one able to another. The ImportRow method of DataTable can greatly improve the performance, and there is not much difference in the amount of data, when the data volume reaches more than 10 thousand rows, it can be significantly increased by several times.

5. serialize data into binary files for easy transmission.
When processing DataSet and able objects, we can serialize them into XML files. If you want to transfer them over the network, XML files may cause memory, network bandwidth, and other resource problems. In this case, we can serialize it into a binary file, which will reduce the number of generated files. The Code is as follows:
Filestream FS = new filestream (@ "xmldata. bin", filemode. Create );
Binaryformatter BF = new binaryformatter ();
BF. serialize (FS, xmldata );
FS. colse ();
The generated binary file is called xmlbinary. If you open it directly with winhex, you can also see some XML tags in it. If the data volume is large, add a line of code:
Xmldata. remortingformat = serializationformat. Binary;
The generated file is called a truebinary file. when processing a large number (more than 10000 rows), the size of the generated file is one of the parts of xmlbinary. The storage mode is automatically saved during serialization, so the process of sorting is very simple. I still don't know how much performance will be lower than the performance of Directly Reading XML.

6. make rational use of the connection pool.
The connection pool plays a major role in improving performance. It is enabled by default. The default min pool size is 0, which is generally set to a relatively small value, for example, 5. By default, the Max pool size is 100, and most web sites are sufficient. The size of a large pool is increased as appropriate.

7. Use sqlclr for development
If you are focusing on the SQL Server series, you should study sqlclr. It is very powerful and can improve performance in many occasions (especially for large enterprise applications ).

8. Access app. config/Web. config through static classes
We have a lot of configuration information stored in the app. config/web. in this case, a static class is created and all attributes are accessed through a static class, which can improve the performance to a certain extent. The static class is instantiated only once, while the app. config/web. config will generate many Io operations.
Public static class mywebconfig
{
 
Static mywebconfig ()
{
Connstring =
Configurationmanager. connectionstrings ["connection"].
Connectionstring;

}
 
Public static string dbconnectionstring
{
Get
{
Return connstring;
}
}
}

 

Well, I will write it here today. I hope to point out any errors and shortcomings. We welcome better comments and make common progress.

#3 floor to timone
There is no need to access app. config/Web. config through static classes. You can use reflector to see the implementation of system. configuration. defaultconfigurationsystem and system. configuration. configurationrecord. The cache has been performed based on the configuration name as the keyword. Otherwise, the Web application will be restarted every time the Web. config file is modified.

#4 Floor 2. use excutereader as much as possible to read data. excutereader is the most efficient, and excutereader is used for all data access in petshop 4.0 of Microsoft, unless you have special requirements for non-connection (such as smartclient ).

The usage of DataReader and DataSet cannot be considered as highly efficient. It depends on the situation. For example, if you perform a batch data operation, you need to access some data repeatedly in this operation, you can read the data to DataSet in advance for the subsequent operations to be used repeatedly. Reduce the number of database accesses.

8. Access APP. Config/Web. Config through static classes
We have a lot of configuration information stored in the APP. config/Web. in this case, a static class is created and all attributes are accessed through a static class, which can improve the performance to a certain extent. The static class is instantiated only once, while the APP. config/Web. config will generate many IO operations.

For a good architecture, I even think that storing configuration information in Web. Config is a bad design, because every time you change the configuration, the Web Application restarts. I think it is better to save the configuration in the defined xml file. When the system starts, the configuration is read into the cache, and then the cache and the configuration file are dependent. This ensures that the server will not be restarted when you modify the configuration.

PS: Well, the garden is really a good place. Even articles can be viewed based on syndrome. Both posts and replies are in good faith.

 

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.