C # High-Performance coding III

Source: Internet
Author: User
Tags oracleconnection

1. GC is prohibited in principle. the Collect method explicitly executes GC. collect () may increase the burden on memory recycling, and may not really recycle the memory. The garbage collection cycle is uncertain, and the garbage collection engine automatically calculates the best garbage collection time. In an application that requires a large amount of memory consumption, if the memory occupied by a specified time point is no longer needed, releasing these memories in time has a significant impact on application performance improvement. In this case, you can force the Garbage Collector to execute the recycle cycle. The GC. Collect method forces the Garbage Collector to perform the garbage collection cycle. Calling the GC. Collect method in an application can force garbage collection and release a large amount of memory that is no longer needed in time. However, too frequent calls to the GC. Collect method can also cause performance problems for applications. Because, when the garbage collection thread is started, the garbage collector suspends all threads currently being executed until the garbage collection thread ends. On the other hand, GC is frequently called. the Collect method also weakens the optimization of the garbage collector engine. In general, the garbage collector can determine the best garbage collection time. In principle, it is not allowed to be used. In special cases, code review is required. 2. If the unmanaged resources are released, we recommend that you use the dispose mode to encapsulate the control of resources (such as Windows handle (HWND) and database connections) that are not managed by the running database. Therefore, both explicit and implicit methods should be provided to release these resources. Implicit control can be provided by implementing the protected Finalize method on the object (for the Destructor syntax in C. When no valid object reference is available, the garbage collector calls this method at a certain time. In some cases, you may want to provide programmers who use this object with the ability to explicitly release these external resources so that these resources can be released before the Garbage Collector releases this object. When external resources are scarce or expensive, programmers can achieve better performance if they are explicitly released when resources are no longer used. To provide explicit control, implement the Dispose method provided by the IDisposable interface. When you complete the operation to use this object, the user of this object should call this method. You can call Dispose even if other references to an object are active. Positive example: // base class mode. public class Base: IDisposable {// implement the Idisposable interface. public void Dispose () {Dispose (true); GC. suppressFinalize (this);} protected virtual void Dispose (bool disposing) {if (disposing) {// other statuses (hosted objects ).} // release status (unmanaged object)} // use the C # destructor to take charge of finalization code ~ Base () {Dispose (false) ;}// subclass mode. public class Derived: Base {protected override void Dispose (bool disposing) {if (disposing) {// release managed resources .} // release unmanaged resources // call the Dispose method base of the base class. dispose (disposing);} // The subclass does not need the Finalize method or the Dispose method without parameters, because it inherits from the base class} 3 if there is an IO operation, it is recommended to use the Buffer description: when I/O operations are performed, the actual length of input and output streams is unknown, for example, network streams. You can initialize a cache first, and then write the Stream information read from the stream to the memory Stream. This improves performance and is safe. Example: publicstaticbyte [] ReadFully (stream Stream) {// Initialize an 8 K cache byte [] buffer = new byte [8192]; using (MemoryStream MS = new MemoryStream ()) {// After the returned results are returned, the Dispose method of the object will be automatically recycled to release the memory while (true) {int read = stream. read (buffer, 0, buffer. length); if (read <= 0) {return ms. toArray ();} ms. write (buffer, 0, read) ;}} 4 empty destructor are not allowed. If the class contains a destructor, the object is created in the Finalize queue. To ensure that the Finalize method can still be called when the object cannot be available. During running, the garbage collector starts a low-priority thread to process the queue. In contrast, objects without destructor do not consume these resources. If the Destructor is empty, this consumption is meaningless and will only result in lower performance. Therefore, do not use empty destructor. 5. recursive and cyclic operations in the loop body to avoid resource consumption. For example, to create a large object, refer to the operations outside the loop body. Note: If an operation is performed to obtain a variable value in the loop body, this operation can be extracted out of the loop and replaced with a temporary variable to avoid unnecessary resource consumption. For example, Database db = new Database (); dataTable dt = db. loadSql ("select id from emps"); foreach (int I = 0; I <5000; I ++) {Emp objEmp = dt. select ("id =" + I, dt );...} Inverse example: foreach (int I = 0; I <5000; I ++) {Database db = new Database (); // reading the Database here is expensive, the operation is irrelevant to the loop. A temporary variable // should be used for recording and Emp objEmp = Business should be used in the variable. findEmp ("id =" + I, db. loadSql ("select id from emps");} positive example: Class objClassa = new Class (); foreach (Class objClassb in Classs) {objClassa. a = objClassb. B ;...} inverse example: foreach (Class objClass in Classs) {Class objClassa = new Class (); objClassa. a = objClassb. B ;...} 6. When the number of loops is certain, the exit condition of the loop cannot be determined multiple times by using the exit condition of the complex statement loop such as a function, for example, complex statements such as functions may cause complex function operations and affect the performance. Positive example: int rowCount = db. rows. count; for (int I = 0; I <rowCount; I ++ ){....} inverse example: for (int I = 0; I <myObject. getItems (). count; I ++ ){.... [csharp] view plaincopyprint?} 7 Exception Handling does not capture exceptions that cannot be handled by the user. Note: For system-based Exception exceptions, after an Exception is caught, you do not know how to handle the Exception. Generally, try again .. catch operation. Example 1: try {....} Catch {} counterexample 2: try {....} Catch {thrownewException ();} after an exception is caught, no operation is performed. It can only hide errors and affect performance. 8. Avoid capturing exceptions inside the loop. Note: To avoid this, it is best to move the Catch range outside the entire loop. Example: try {for (int I = 0; I <1000; I ++) {dt. rows [I] = ...;} Catch {...} Inverse example: for (int I = 0; I <1000; I ++) {try {dt. rows [I] = "";} catch {...} 9 use try catch finally or using blocks to ensure the release of unmanaged resources. Note: using ensures that the objects executing the IDisposable interface are released immediately when the block is exited, it is mainly to prevent the possible cause of forgetting to close the database connection.. net executable program. Positive example: using (OracleConnection cn = new OracleConnection (connectionString) {OracleCommand cmd = new OracleCommand (); PrepareCommand (cmd, cn, commandType, commandText, commandParameters ); // create the DataAdapter & DataSet OracleDataAdapter da = new OracleDataAdapter (cmd); DataSet ds = new DataSet (); // fill the DataSet using default values for DataTable names, etc. da. fill (ds); cmd. parameters. clear (); Return ds. tables [0];} 9 threads avoid manual creation of threads in asp.net, which consumes too much resources if necessary, use CLR thread pool 10 for serialization to avoid serialization and deserialization of a large amount of data. Note: serialization and deserialization consume CPU resources. In Asp.net programming, objects are saved to viewstate. serialization is required. objects are obtained from viewstate and deserialization is required. Serialization and deserialization are also required for web service calls. Note that the calling interface of web service should avoid DataSet serialization as simple as possible, and serialization should be performed after DataSet is replaced by Entity List: the DataSet object contains a lot of structured content. First, the DataSet is converted to ILIST, which consumes less resources during serialization. Positive example: IList list = base. select ("", null); ViewState ["List"] = list; inverse example: DataSet ds = newDataSet (); ds = base. getDataSet ("", ""); ViewState ["Data"] = ds; 11 reflection avoids reflection in loops and recursion. Note: Reflection consumes many resources, multiple reflections in loops and Recursion have a significant impact on performance. ToString is implemented in the custom type to avoid reflection. Note: Object. ToString uses reflection. You can implement the ToString method when customizing the type to avoid reflection by using the ToString of the base class. 12 cache (1) do not store too many variables in Caching. Note: excessive information is stored in the cache, And the cache hit rate is low, resulting in frequent cache exchanges. (2) store less changed data in the cache. Note: The cache stores less changed data and is used for multiple times, reduce the resource consumption that needs to be obtained from the database or configuration file for each use. Data that is infrequently used and does not consume too much resources cannot be stored in the cache. 13 The Session cannot store or enlarge Data Objects. For example, when DataTable and DataSet SessionState use the InProc method, the Session is actually stored in the server's memory by Cache, therefore, when a large amount of data is stored in the Session, the memory of the W3WP process is too high. When StateServer or SQL Server is used, each request will be serialized and deserialized. For example, DataTable dt = GetData (); Session ["data"] = dt; when session is not required on the page, if you want to disable the <sessionState mode = "Off"/> <@ % EnableSessionState = "false" %> function when you do not need to modify the objects in the Session, if the EnableSessionState of the Page is set to read-only without writing, the EnableSessionState can be set to read-only to improve concurrency. <% @ Page EnableSessionState = "ReadOnly" %> 14 ViewState the object cannot be enlarged, for example, DataTable and DataSet Description: If the ViewState object contains too much information, the page may be too large, Network Transmission is affected. Complex objects are stored in ViewState objects. serialization and deserialization of objects are required to affect the performance. Inverse example: DataTable dt = GetData (); ViewState ["data"] = dt; 15 if no dynamic data is displayed, disable the ViewState function. Description: Based on the page and control details, if ViewState information is not required, EnableViewSate is set to False. 16 Data paging is not required for queries that return more than 1000 rows of data. Instead, pagination is required for data query, take only one page of data to the front-end. Note: After all data is retrieved from the database, it is stored in ASP. NET. for queries with a large amount of data returned, this will bring about two problems: 1. the application server consumes a large amount of memory because a large DataTable needs to be generated; 2. It consumes a lot of CPU on the application server, because you need to select the data page to be output in a large DataTable. For Oracle databases, you can use ROWNUM in SQL statements to implement paging. Positive example: use this SQL statement to obtain 20 rows of data FROM 81st to 100. The result is displayed on the front-end as one page: SELECT * FROM (SELECT. *, rownum rn from (SELECT * FROM TABLE_NAME) a where rownum <= 100) where rn> = 81 counterexample: Use SELECT * FROM TABLE_NAME to obtain all data and bind it to the DataGrid, depends on the DataGrid for paging. 17 client scripts use client scripts to determine user input Description: user input required items are judged at the client first, and the server verifies the items again, this reduces the number of days when the server determines that the page cannot be passed back. 18 Page (1) Avoid using Page. DataBind Description: Page. DataBind recursively calls DataBind on each control of the Page. (2) Avoid using DataBinder. eval Description: DataBinder. eval uses the reflection positive example: <% # (DataRowView) Container. dataItem) ["field1"] %> counterexample: <% # DataBinder. eval (Container. dataItem, "field1") %> avoid too much content on the page during the design of the page function, it is recommended to compress the js files when the web application is released. Note: the size of the js files processed by the js compression tool is about half of the size of the original files, this reduces the amount of data transmitted to user request pages.

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.