Performance optimizations in C # [no-effort]

Source: Internet
Author: User
Tags cos

Http://www.cnblogs.com/blqw/p/3619132.html

Reduce duplicate code

This is the most basic optimization scheme, minimizing the duplication of things and letting them do it only once

More common is this code, the same math.cos (angle) and Math.sin (angle) have done 2 times

Private point rotatept (double angle, point pt) {point     PRet = new Point ();     angle =-angle;     Pret.x = (int) ((double) pt. X * Math.Cos (angle)-(double) pt. Y * Math.sin (angle));     PRET.Y = (int) ((double) pt. X * Math.sin (angle) + (double) pt. Y * Math.Cos (angle));     return pRet;}

After optimization

Private point RotatePt3 (double angle, point pt) {point    PRet = new Point ();    angle =-angle;    Double sin_angle = Math.sin (ANGLE);    Double cos_angle = Math.Cos (ANGLE);    Pret.x = (int) (Pt. X * cos_angle-pt. Y * sin_angle);    PRET.Y = (int) (Pt. X * Sin_angle + pt. Y * cos_angle);    return pRet;}

There is another way to instantiate an object in a method, but this object can be reused.

public static string Convertquot (string html) {    regex regex = new Regex ("& (quot| #34);", Regexoptions.ignorecase) ;    return regex. Replace (HTML, "\");}

After optimization

readonly static Regex replacequot = new Regex ("& (quot| #34);", Regexoptions.ignorecase | regexoptions.compiled);p ublic static string Convertquot (string html) {    return replacequot.replace (HTML, "\");}

There is also an unnecessary initialization, such as before calling out parameters, which do not need to be initialized

public bool Check (int userid) {    var user = new User ();    if (GetUser (userid,out user))    {        return user. Level > 1;    }    return false;}

The new User () here is an unnecessary operation,

After optimization

public bool Check (int userid) {    user user;    if (GetUser (userid,out user))    {        return user. Level > 1;    }    return false;}
Don't be superstitious. Regular expressions

Just in the first Li Zili, speaking of an expression (Regex) object, I'm going to say it by the way.

Many people think regular expressions are fast, very fast, super fast.

Although the regular expression is very fast, but do not superstition him, do not believe you see the chestnut below

Method 1public static string ConvertQuot1 (string html) {    return HTML. Replace (""", "\" "). Replace ("& #34;", "\" ");} readonly static Regex replacequot = new Regex ("& (quot| #34);", Regexoptions.ignorecase | regexoptions.compiled);//method 2public static string ConvertQuot2 (string html) {    return replacequot.replace (HTML, "\" ");}

How many people think that the regular expression is faster, give a hand??

The result is a 10w cycle time , even if 10 replace with, also better than regex, so do not superstition him

Method 1public static string ConvertQuot1 (string html) {    return HTML. Replace ("0", ""). Replace ("1", ""). Replace ("2", ""). Replace ("3", ""). Replace ("4", ""). Replace ("5", ""). Replace ("6", ""). Replace ("7", ""). Replace ("8", ""). Replace ("9", "");} readonly static Regex replacequot = new Regex ("[1234567890]", Regexoptions.ignorecase | regexoptions.compiled);//method 2public static string ConvertQuot2 (string html) {    return replacequot.replace (HTML, "") ;}

convertquot1:3518
convertquot2:12479

And finally show you a real, cup of chestnut.

htmlstring = Regex.Replace (htmlstring, @ "< (. [ ^>]*) > "," ", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "([\ r \ n]) [\s]+", "", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "-and", "", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "<!--. *", "", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (quot| #34);", "\" ", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (amp| #38);", "&", Regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (lt| #60);", "<", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (gt| #62);", ">", Regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (nbsp| #160);", "", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (iexcl| #161);", "\xa1", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (cent| #162);", "\xa2", regexoptions.ignorecase); htmlstring = ReGex. Replace (htmlstring, @ "& (pound| #163);", "\xa3", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "& (copy| #169);", "\xa9", regexoptions.ignorecase); htmlstring = Regex.Replace (htmlstring, @ "(\d+);", "", regexoptions.ignorecase);
Rational use of regular expressions

It says the efficiency of regular expressions is not high, not to say don't use him, at least the regular expression of the role is not so much

If you must use regular expressions, you also need to note that can be static global public as far as possible global public

readonly static regex regex = new Regex ("[1234567890]", regexoptions.compiled);

Notice his second argument regexoptions.compiled note is that you specify that the regular expression be compiled into an assembly. This results in faster execution, but increases the startup time.

In layman's terms, adding this enumeration will cause the initialization of the Regex object to be slow, but the execution of the string lookup is faster, does not use, the initialization is many, the query is slow

Before the difference is quite large, the code is not compared, interested can try their own difference how much

There are also some enumerated items that are not determined to have an impact on performance, but it would be better to use them in a regular basis.

    • Regexoptions.ignorecase//Specifies a case-insensitive match that does not need to be set if there are no letters in the expression
    • Regexoptions.multiline//multi-line mode.  Change the meaning of ^ and $ .... If there is no ^ and $ in the expression, you do not need to set
    • Regexoptions.singleline//Specify single-line mode.  Change the meaning of the point (.) .... If there is no in the expression, you do not need to set
Let the compiler pre-process the calculation of constants

When the compiler compiles a program segment, if it finds that some of the operations are constant to constant, then he will complete the calculation during compilation, so that the program does not have to be repeated at the time of execution.

Like what

But the compiler is not that smart sometimes.

This time, we need help.

Give him a parenthesis and let him know that constants should be calculated first so that they can be shipped during compilation.

string comparison

This may be a lot of people know, but still mention

string s = ""; 1) if (s = = "") {}2) if (s = = string. Empty) {}3) if (string. IsNullOrEmpty (s)) {}4) if (s! = null && s.length ==0) {} 5) if ((s+ ""). Length = = 0) {}  

The slowest 3 faster 4,5 the fastest

Almost no difference 4,5 almost no difference

However, this only applies to comparing null and empty strings, if continuous whitespace is string. Isnullorwhitespace is the quickest, but there's no one in this method 2.0.

So 2.0 can do this (s+ ""). Trim () = = 0

The key here is S + "" This operation can convert null to ""

Note the second argument can only be "" or a string. Empty such an accumulation is almost no time consuming, if the second parameter is "" (a space) this time is much more than

string concatenation

String accumulation, this truth and the same as the regex, do not blindly worship StringBuilder

In a large number of (or uncertain) string splicing, StringBuilder can actually play a role in accelerating

and a few fixed string accumulation of time do not need to StringBuilder, after all, StringBuilder initialization also takes time

Thanks for the description provided by the remnant pupa Bo 2014-03-24 16:45

PS: This paragraph I do remember I wrote it, do not know how, the time of the issue is gone.

There is also a string. Concat method, the method can be small amplitude optimization program speed, the amplitude is very small

Him and string. The difference between joins is that there are no spacing symbols ( I used to use string. Join ("", a,b,c,d), don't tell me I'm the only one doing this .

Another frequently encountered string concatenation

public string Joinids (list<user> users) {    StringBuilder sb = new StringBuilder ();    foreach (var user in users)    {        sb. Append ("'");        Sb. Append (user. ID);        Sb. Append ("',");    }    Sb. Length = sb. Length-1;    Return SB. ToString ();}

For this scenario there are 2 optimization scenarios

For more than 3.5 you can use LINQ assistance directly, which is less code, but has a relatively poor performance

public string Joinids (list<user> users) {    return "'" + string. Join ("', '", users.) Select (it = it). ID)) + "'";}

For non-3.5 or very high performance requirements

public string Joinids (list<user> users) {    var ee = users. GetEnumerator ();    StringBuilder sb = new StringBuilder ();    if (EE. MoveNext ())    {        sb. Append ("'");        Sb. Append (EE. current.id);        Sb. Append ("'");        while (EE. MoveNext ())        {            sb. Append (", '");            Sb. Append (EE. current.id);            Sb. Append ("'");        }    }    Return SB. ToString ();}
The judgment of the bool type returns

This phenomenon is common in novice programmers.

Notation 1if (state = = 1) {    return true;} else{    return false;} notation 2return state = = 1? true:false;//after optimization return state = = 1;
Type of judgment

There are 2 types of judgments of general type

1, this belongs to the code is good to write, but the performance is relatively low, the reason is GetType () time consumes a lot of time

Type type = obj. GetType (); switch (type. Name) {case    ' Int32 ': Break        ;    Case ' String ': Break        ;    Case ' Boolean ': Break        ;    Case ' DateTime ': Break        ;    ...    ...    Default: Break        ;}

2, this attribute writes code troublesome, but the performance is very high type

if (obj is string) {}else if (obj was int) {}else if (obj is DateTime) {}......else{}

In fact, there is a middle way, both to ensure that performance and can be relatively good writing

IConvertible conv = obj as iconvertible;if (CONV! = null) {    switch (conv. GetTypeCode ())    {case        Typecode.boolean: Break            ;        Case Typecode.byte: Break            ;        Case Typecode.char: Break            ;        Case Typecode.dbnull: Break            ;        Case Typecode.datetime: Break            ;        Case Typecode.decimal: Break            ;        Case typecode.double: Break            ;        Case Typecode.empty: Break            ;        Case typecode.int16: Break            ;        Case TYPECODE.INT32: Break            ;        ...        ...        Default: Break            ;    }} else{    //handling other types}

In most cases this can be used if you have a type that implements the IConvertible and then returns to Typecode.int32 is no longer within the scope of this discussion.

Using enumerations as Indexes

Here is a real example, in order to highlight the focus, made a partial modification, delete the redundant branch, the source code in more than 4

Enum templatecode{    None = 0,    Head = 1,    Menu = 2,    Foot = 3,    Welcome = 4,}public string gethtml (Template Code tc) {    switch (TC)    {case        templatecode.head:            return GetHead ();        Case Templatecode.menu:            return GetMenu ();        Case Templatecode.foot:            return Getfoot ();        Case Templatecode.welcome:            return Getwelcome ();        Default:            throw new ArgumentOutOfRangeException ("TC");}    }

After optimization

readonly static func<string>[] gettemplate = inittemplatefunction ();p rivate static func<string>[] Inittemplatefunction () {    var arr = new func<string>[5];    ARR[1] = GetHead;    ARR[2] = GetMenu;    ARR[3] = getfoot;    ARR[4] = Getwelcome;
return arr;} public string gethtml (Templatecode tc) { var index = (int) TC; if (index >= 1 && index <= 4) { return gettemplate[index] (); } throw new ArgumentOutOfRangeException ("TC");

Sometimes, however, enumerations are not necessarily sequential numbers, so you can also use dictionary

readonly static Dictionary<templatecode, func<string>> templatedict = inittemplatefunction ();p rivate Static Dictionary<templatecode, func<string>> inittemplatefunction () {    var ditc = new dictionary< Templatecode, func<string>> ();    DITC. ADD (Templatecode.head, gethead);    DITC. ADD (Templatecode.menu, getmenu);    DITC. ADD (Templatecode.foot, getfoot);    DITC. ADD (Templatecode.welcome, getwelcome);    return DITC;} public string gethtml (Templatecode tc) {    func<string> Func;    if (Templatedict.trygetvalue (tc,out func))    {        return func ();    }    throw new ArgumentOutOfRangeException ("TC");

This kind of optimization is very useful when the branch is more, and less when the function is limited.

Character type char, processing tips for branching judgment

This part of the content is more complex, and the scope of application is limited, if you usually do not have to ignore the

When working with string objects, it is sometimes necessary to determine the value of char and do further work

public string Show (char c) {    if (c >= ' 0 ' && C <= ' 9 ')    {        return ' number ';    }    else if (c >= ' a ' && c <= ' z ')    {        return ' lowercase letter ';    }    else if (c >= ' A ' && C <= ' Z ')    {        return ' uppercase ';    }    else if (c = = '/' | | c = = ' \ \ ' | | c = = ' | ' | | c = = ' $ ' | | c = = ' # ' | | c = = ' + ' | | c = = '% ' | | c = = '        & ' | | = = '-'        | | c = = ' ^ ' | | c = = ' * ' | | c = = ' = ')    {        return ' special symbol ';    }    else if (c = = ', ' | | c = = '. ' | | c = = '! ' | | c = = ': ' | | c = = '; ' | | c = = '? ' | | c = = '        "' | | c = = ' \ ')    {        return ' punctuation ';    }    else    {        return "other";    }}

There is a space for the optimization of time, although the space for time, but the actual wasted space is not much, because char up to only 65536 length

readonly static byte[] Charmap = Initcharmap ();p rivate static byte[] Initcharmap () {var arr = new Byte[char.    MaxValue];    for (char i = ' 0 '; I <= ' 9 '; i++) {arr[i] = 1;    } for (char i = ' a '; I <= ' z '; i++) {arr[i] = 2;    } for (char i = ' A '; I <= ' Z '; i++) {arr[i] = 3;    } arr['/'] = 4;    arr[' \ \ '] = 4;    Arr[' | '] = 4;    arr[' $ '] = 4;    arr[' # '] = 4;    arr[' + '] = 4;    arr['% '] = 4;    arr[' & '] = 4;    arr['-'] = 4;    arr[' ^ '] = 4;    arr[' * '] = 4;    arr[' = '] = 4;    Arr[', '] = 5;    arr['. '] = 5;    arr['! '] = 5;    arr[': '] = 5;    Arr['; '] = 5;    arr['? '] = 5;    Arr[' "'] = 5;    arr[' \ '] = 5; return arr;}        public string Show (char c) {switch (Charmap[c]) {case 0:return "other";        Case 1:return "number";        Case 2:return "lowercase letter";        Case 3:return "capital letters";        Case 4:return "special symbol";        Case 5:return "punctuation"; DefauLt:return "Other"; }}

The original only part of the special symbol needs to be judged 12 times, modified only once to determine the results can be obtained

The chestnuts in this regard are also used in my JSON Component (code) (article-by-piece)

<summary>///<para> contains 1: Can be the character of the head </para>///<para> contains 2: You can </para>///the character of a word <para > contains 4: Can be a number of characters </para>///<para> equals 8: White space character </para>///<para> contains 16: Escape character </para>///< para></para>///</summary>private readonly static byte[] _wordchars = new Byte[char. MaxValue];p rivate readonly static sbyte[] _unicodeflags = new sbyte[123];p rivate readonly static sbyte[,,] _datetimewords    Static Unsafejsonreader () {for (int i = 0; i < 123; i++) {_unicodeflags[i] = 1; } _wordchars['-'] = 1 |    4; _wordchars[' + '] = 1 |    4; _wordchars[' $ '] = 1 |    2; _wordchars[' _ '] = 1 |    2;        for (char c = ' a '; c <= ' z '; C + +) {_wordchars[c] = 1 | 2;    _UNICODEFLAGS[C] = (sbyte) (C-' a ' + 10);        } for (char c = ' A '; c <= ' Z '; C + +) {_wordchars[c] = 1 | 2;    _UNICODEFLAGS[C] = (sbyte) (C-' A ' + 10); } _wordchars['. '] = 1 | 2 |    4; for (char C = ' 0 '; c <= ' 9 '; C + +) {       _WORDCHARS[C] = 4;    _UNICODEFLAGS[C] = (sbyte) (C-' 0 ');    }//Scientific counting Method _wordchars[' E '] |= 4;    _wordchars[' E '] |= 4;    _wordchars["] = 8;    _wordchars[' \ t '] = 8;    _wordchars[' \ r '] = 8;    _wordchars[' \ n '] = 8;    _wordchars[' t '] |= 16;    _wordchars[' R '] |= 16;    _wordchars[' n '] |= 16;    _wordchars[' F '] |= 16;    _wordchars[' 0 '] |= 16;    _wordchars[' "'] |= 16;    _wordchars[' \ '] |= 16;    _wordchars[' \ \ '] |= 16;    _wordchars['/'] |= 16;    String[] A = {"Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "April", "Sep", "Oct", "Nov", "Dec"};    String[] B = {"Mon", "Tue", "Wed", "Thu", "Fri", "sat", "Sun"};    _datetimewords = new sbyte[23, 21, 25];        for (sbyte i = 0; i < a.length; i++) {var d = a[i];    _datetimewords[d[0]-d[1, [d[2]-[]] = (sbyte) (i + 1);        } for (SByte i = 0; i < b.length; i++) {var d = b[i];    _datetimewords[d[0]-d[1, d[2]-(sbyte)-(i + 1); } _datetimewords[' G '-A, ' m '-A, ' t '-"-" = sbyte. MaxValue;}

Performance optimizations in C # [no-effort]

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.