Introduction to. Net Operation Efficiency

Source: Internet
Author: User

. Net execution efficiency has been a hot topic for a long time. It focuses on garbage collector (GC), managed code, JIT (just in-time) and so on.

First, GC. In fact, the GC used in. Net is a modern and efficient GC, which is much different from the GC of Lisp. It uses a rather complex algorithm. GC can make it easier for programmers to focus more on the main logic of the application, instead of consuming time for memory allocation and release, of course, the impact of GC on performance cannot be ignored. When GC is running, other jobs will stop, but fortunately it will not run frequently.

Cute JIT, he compiled il into local code when the application was first executed, which of course consumes CPU time, but he has more advantages than him. JIT does not compile all the code into the local code at one time, but compile the method into the local code only when the program calls the method (process. JIT also optimizes different platforms, which cannot be achieved by traditional compilers. Theoretically, different JIT programs can be used to run cross-platform. net programs. For example, Mono (for a project that implements the. NET Framework on Linux, see http://www.go-mono.com/. the latest version is 0.3 ).

However, cross-platform performance is not as good as you think. It can be seen from Java's "one-time compilation, running everywhere" called "One-time compilation, debugging everywhere" by runtime. This is due to the huge differences in operating systems. Therefore, cross-platform applications must be optimized for different platforms to effectively improve program stability and efficiency.

Microsoft has done a good job of JIT. At least the current CLR 1.1 is much faster than JVM 1.4. Perhaps the version 1.5 JVM named Tiger (TIGER) will greatly improve the efficiency. However, the runtime compilation performance is not very important in enterprise-level applications, so do not care too much about it.

In addition, there are some performance improvement skills:

 

I. String and stringbuilder

When a string needs to change frequently, use stringbuilder. Although stringbuilder provides fewer functions. One way to fold is to convert the tostring () method of stringbuilder to string (Note :. in NET 1.1, no explicit or implicit conversion can convert stringbuilder to string. You can only call the tostring () method of stringbuilder .).

String is actually an unchangeable data type, and the memory allocated in the managed heap just meets the string length. Modifying a string is actually creating a new string. If necessary, copy the old string to the new string. Obviously, when the string content is constantly added, the program becomes less efficient and the old string becomes garbage, which increases the number of GC operations. Stringbuilder usually allocates more memory than needed. You can explicitly specify this length in a stringbuilder overload. The required memory is re-allocated only when the length of the extended string is used. If the new length is not explicitly specified, it is about twice the old length (Note: Microsoft does not provide clear documentation, 2 times is obtained by observing Memory changes .).

It can be seen that the use of stringbuilder can greatly reduce the memory reallocation, the number of copies, and the number of garbage. However, this only applies to append substrings and replace characters, and the efficiency of deleting and inserting substrings is still low.

Note that the system. Text namespace must be referenced when stringbuilder is used.

Array array and arraylist are similar to string and stringbuilder.

 

2. datareader Indexer

Datareader has two types of indexers: int and string. The two indexers use different algorithms. In a simple iterative test, the int indexer is about five times faster than the string indexer. This is certainly not accurate, but at least it indicates that the int index is more efficient. Therefore, we recommend that you use the int indexer. However, the program using the string indexer has higher readability. There is a good way to use constants to define the indexes of the int indexer. For example:

Private const int field_table1_id = 0;
//....
Response. Write (datareader [field_table1_id]. tostring ());

Note that when changing the SELECT query, do not forget to check whether the constant still corresponds to a correct field.

 

3. datareader and Dataset

Datareader is a read-only forward stream, and dataset is a dataset with a complex structure. Filling datareader is much faster than filling dataset. (Dataset is filled with datareader) But dataset is disconnected, and datareader keeps the database connection open. Database Connection is an expensive resource. Therefore, use dataset or a strongly-typed dataset derived from dataset whenever possible. In addition, do not use datareader when passing datasets (for example, passing between layers, WebService sending and receiving datasets.

Use datareader in the following cases

  • Simple iteration of a dataset
  • Quick access to datasets with simple data structures
  • Bind data to simple controls

When iterating datareader, try to avoid implementing too much logic in the iteration process.

 

Iv. Use of high-cost resources

As mentioned above, database connection is a high-cost resource. It should be set up as late as possible and disabled as early as possible. Use try... in C... Catch... Finally blocks ensure that the database connection is closed in finally, but sometimes you may forget to write code such as connection. Close. Another method is to use the using statement, for example:

Using (sqlconnection connection = new sqlconnection (connectionstring ))
{
Connection. open ();
//...
}

After the scope is exceeded, CLR automatically calls the dispose () method. (The objects in the using statement must implement the idisposable interface.) This method ensures that the close () method is executed, but it is not conducive to exception handling. Two methods can be used to nest using in try, for example:

Try
{
Using (sqlconnection connection = new sqlconnection (connectionstring ))
{
Connection. open ();
//...
}
}
Catch (exception ex)
{
//...
}
Finally
{
//...
}

In addition, when processing the dataaccess layer in a multi-tier application, the class should implement the idisposable interface.

 

5. pointer

A conventional question, please remember: You are programming in the managed environment provided by. net, so if it is not necessary and there are plenty of reasons, do not use pointers. In C ++, pointers are flexible but dangerous. In. net, some pointer functions can be used as alternatives. For example, function pointers can be replaced by delegation. One advantage of using a delegate is that the delegate type is highly secure. However, pointers are inevitable for some tasks, such as writing a debugger.

When you use pointers, CLR determines that you know exactly what you are doing. Because the pointer will bypass all runtime security checks.

Another point is that programs that contain Insecure code (using pointers is one of them) may be banned from running (the final decision is in the hands of users ).

 

Vi. Other supplements

In. net, you can use the exception mechanism as you like. Of course, pay attention to the processing level. It will not have a big impact on performance. This is different from C ++, So C ++ programmers can safely use it.

Pay attention to future binding. Avoid using this technology whenever possible.

 

 

Bibliography and Website:

C # advanced programming Tsinghua University Press

ASP. NET advanced programming Tsinghua University Press

. NET Framework advanced programming Tsinghua University Press

Ado. Net advanced programming China Power Press

. NET Programming core programming, Tsinghua University Press

Msdn (http://www.microsoft.com/msdn)

Http://www.csdn.net (csdn)

Developer Club (http://www.dev-club.com)

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.