C # commonly used optimization summary

  1. 1. Creating an object
    . 1.1 avoid unnecessary object creation;
    due to the higher cost of garbage collection, so the C # program to develop a basic principle to follow is to avoid unnecessary object creation
    1.2 avoid loop to create objects;.
    If the object does not with each cycle will change state, then create objects repeatedly in a loop will bring performance loss. Efficient to create an object outside the loop mentioned
    1.3 Creating the logical objects in the corresponding branch;.
    If the object was only used in only certain logic branch, it should only create objects in the logical branch
    1.4 to avoid creating a constant. objects;
    1.4.1 following example, a large number of new decimal (0) the program code is present, which can lead to frequent small objects and creates recovery; Decimal.Zero correct approach is to use a constant
    decimal _qtzf = new decimal (0) ; // other payment
    decimal _zje = new decimal (0) ; // total amount of
    decimal _zhzf = new decimal (0) ; // account to pay
    decimal _tczf = new decimal (0) ; // overall pay
    decimal _xjzf = new decimal (0) ; //cash payment

    2 .string stringBuilder and rational use of
    the following example, String class is the same, using the + operator creates a connection string will result in a new string. If the string is not a fixed number of connections, results in the creation of a new space to store the connection string is used in multiple cycles of "+" cause memory cycle is opened. For example, in a loop, StringBuilder class should be used to do the work string concatenation. Because there is an internal StringBuilder StringBuffer, connecting each dispensing operation is not a new string space
    var strSFXMMCs = "";
    strSFXMMCs strSFXMMCs + = "Payment illness" + (printObject.DBZFJE ?? "0" ) + "<br /> ";
    strSFXMMCs = strSFXMMCs +" medical assistance "+ (?? printObject.JZJJZF" 0 ") +" <br /> ";
    strSFXMMCs = strSFXMMCs +" supplementary medical "+ (printObject.GRBCJJZF ??" 0 " ) +" /> <br ";
    strSFXMMCs = strSFXMMCs +" account balance "+ (?? printObject.ZHYE" 0 ") +" /> <br ";
    strSFXMMCs = strSFXMMCs +" Corporate & emsp; member "+ (printObject.

    strSFXMMCs = strSFXMMCs + "other funds" + (?? printObject.QTJJ "0") + "<br />";
    strSFXMMCs = strSFXMMCs + "guaranteeing rescue" + (printObject.DBJZJEZF ?? "0" ) + "< br /> ";

    3. The non-null code object is determined
    in the following example,
    pi.SFXZMC = objSFXZ.FirstOrDefault (A => == a.SFXZBM pi.SFXZBM) .MC;
    correct wording
    IF (! = Null objSFXZ)
    pi.SFXZMC objSFXZ.FirstOrDefault = ( a => a.SFXZBM == pi.SFXZBM) ?. MC;

     

    5.EF precautions in use AsNoTracking, Any, AsParallel, Aggregate

    EF.Functions.Like (p.Name, "% Yan%") with EF.Contains ( "swallow")

    1. Use the latest version of the EF


    2. Disable lazy loading


    3. Greed load (also known as multi-table is pre-loaded database queries)


    4. Learn ToList (), .AsEnumerable (), AsQueryable () difference

    4.1 AsEnumerable () delay the execution, it is not performed immediately. When you call .AsEnumerable (), in fact, nothing happened.

    4.2 .ToList () immediately. When you need to manipulate the results, with .ToList (), otherwise, if only for the query result set no further use, and can delay the execution, use .AsEnumerable () / IEnumerable / IQueryable

    4.3. AsEnumerable () Although the delay in the implementation, but still access the database, and .ToList () directly to obtain results in memory. For example, we need to show employees of the two departments, the department can first be placed out in the List, and then turn out employees of various departments, the efficiency is higher then visit because there is no access to the database each time to remove the department.
    4.4 IQueryable implements IEnumberable interface. However IEnumerable <T> into IQueryable <T> After much faster. The reason:
    the difference between IQueryable interface IEnumberable interfaces: IEnumerable <T> generic class in their calling and Take SKip and other extension methods before the data has been loaded in the local memory, while the IQueryable <T> is Skip, take these methods after expressions translated into T-SQL statements SQL server to send commands again, it is not all the data are loaded into memory only to conditional filtering.
    4.5 IEnumerable is running Linq to Object, to force all of the data read from the database into memory first

     

    5. Optimize operation AsNoTracking ()
    5.1. EF current version is 6.0, the database entity model generation are DbSet <T> type
    5.2. For data access by default models are tracing is enabled
    for read-only operations, it is strongly recommended to use AsNoTracking data acquisition, so save time to visit EF Context, it will greatly reduce the time required to obtain data.
    And because there is no context by tracking the cache, so the data is timely made to date, more conducive to high demand for certain timeliness of data data query
    6.EF use SqlQuery

    7. About AsNonUnicode
    var = db.User.Where Query (A => == a.name DbFunctions.AsNonUnicode ( "Mongo"))
    to generate sql: select * from user where Name = N'mongo ';
    knows is N string as stored in Unicode format. Because .Net string are Unicode format, an N-type in SQL Where clause side when the other side when no N-type, then will perform the data conversion, that is, if you have an index in this table when fail Instead cause full table scan. By EntityFunctions.AsNonUnicode way to tell .Net to be treated as a non-Unicode, SQL statements, both sides are not generated at this time N-type, it would not be more data conversion, that will not cause more full table scan. Therefore, when a large amount of data without converting cause unexpected results, thus performing the comparison string search or recommendation method AsNonUnicode () to improve the query performance
    8. About Any
    Description: determining whether there is a set of elements satisfying a condition; not delayed. (If the condition is empty, as long as the collection is not empty returns True, otherwise False). There are two forms, namely in the form of a simple form and conditional
    p.TYBZ = ret.Where (_ => _.TYBZ == 0) .ToList () Count> 0 0:.? 1;
    optimized:
    p.TYBZ = ret.Any (_ => _.TYBZ == 0) 0: 1;?

    9. With regard to AsParallel, Aggregate

    10. Recommends that instead of using ViewModel entity Model
    query field reduction (probably several) on query performance
    11. The rational use of EF extensions

    12. Batch search function

    13. query caching feature
    we are now back project rights management module, all menu items are written into the database, menu items show users different roles acquired varies.
    Project navigation menu that is frequently accessed database leads to poor performance (grade 1 starting to get a menu, and then get through the level 2 menu Level 1, Level 2, Level 3 acquired)
    solution is the first query to the data cache setting up Cache time, and then some time to research this data (such as an entire page refresh) directly to obtain in the cache, thereby reducing the interaction with the database.
    Code is as follows:
    var = db.User.Where Users (U => u.Id>. 5) .FromCache (CachePolicy.WithDurationExpiration (TimeSpan.FromSeconds (30)));
    If the query is repeated within 30 seconds, from the cache will reading, does not query the database

    14 to distinguish between true and false tab tab
    in the following example:
    . query.ToList () Skip ((the PageIndex -. 1) * the PageSize) .Take (the PageSize);
    query.Skip ((the PageIndex -. 1) * PageSize) .Take (PageSize) .ToList ( );
    short of 15. Note that the transaction
    when using a transaction, we try to put things into a transaction unrelated to the implementation of external affairs, such as the statement (outside of the query or other matters) ,
    If you let a transaction execution time is too long, it is easy to cause problems resource deadlock, when the measured pressure, the wrong resources locked immediately appear

     

     

Guess you like

Origin www.cnblogs.com/56982173513871739239lex/p/11687643.html