C # code optimization performance optimization

Source: Internet
Author: User

In my own project, I began to gradually get in touch with the optimization part of the program and had a lot of understanding about it. Code Writing standardization helps the team members quickly understand your code. Code optimization helps to make the program run faster. So here are some specific text instructions and my own dummies.

 

C # code optimization

1. Float is not faster than double

An important principle of software testing and optimization is based on experiments. Everything is subject to the results of the experiments. I once assumed that the float type has few digits, it should be faster than double type. However, experiments prove that this idea is wrong;

Evaluate the knowledge of the following code:

 

Int I, J;

Float F1 = 7.125f, f2 = 7.125f;

Double d1 = 7.125d, D2 = 7.125d;

 

Datetime dt = datetime. now;

 

For (I = 0; I <1000000000; I ++)

{

F1 = f2/2.2f + 12.3333f;

}

 

TimeSpan ts = DateTime. Now-dt;

 

MessageBox. Show (ts. ToString ());

 

Dt = DateTime. Now;

For (I = 0; I <1000000000; I ++)

{

D1 = d2/2.2d + 12.3333d;

}

 

TS = datetime. Now-dT;

 

MessageBox. Show (TS. tostring ());

 

Run this code and the conclusion is that the float and double types have the same computing speed. Therefore, if the double type is changed to float, the program speed will not be improved;

If this is the case, we can still accept float, because after all, float saves a lot of memory;

However, float is very disappointing. I found a critical weakness of him. It takes too long to convert float into an int, it takes twice as much time to convert the double type into an integer;

To verify this, change the code just now to the following:

Int I, J;

Float F1 = 7.125f, f2 = 7.125f;

Double d1 = 7.125d, D2 = 7.125d;

 

 

Datetime dt = datetime. now;

 

For (I = 0; I <1000000000; I ++)

{

// F1 = F2/2.2f + 12.3333f;

J = (INT) F1;

}

 

TimeSpan ts = DateTime. Now-dt;

 

MessageBox. Show (ts. ToString ());

 

Dt = DateTime. Now;

For (I = 0; I <1000000000; I ++)

{

// D1 = d2/2.2d + 12.3333d;

J = (int) d1;

}

 

TS = datetime. Now-dT;

 

MessageBox. Show (TS. tostring ());

 

In our Configuration component code, floating point-to-integer operations are everywhere (because computer graphics require rastering, the pixel coordinate must be an integer). Therefore, if we use the float type, the Code may be very slow;

 

2. Right Shift and pre-calculation optimization are effective

Today, there is a call on the internet, saying that the current compiler is smart enough to automatically perform some common Optimizations to the code. Some old optimization methods are no longer applicable, for example, the right shift is used to replace division and pre-calculation;

Unfortunately, although C # Today has some compilation optimization functions, it is not as intelligent as the smart compiler that has been praised on the network. It has been found through experiments that, replacing division and pre-calculation with right shift is obviously not out of date;

After experiments, we found that for an integer, moving one right is faster than dividing two, which is about 6% faster.

As for pre-calculation, experiments have found that expression writing affects the pre-calculation function of C #. For example, the I = J * (2D/3d) compiler can optimize it, during compilation, the compiler first obtains the 2D/3D value, and then returns the result 0.66... Compile to the target code, so the actual compiled code is equivalent to I = J * 0.66 ...; However, if I = J * 2D/3d, the compiler will not optimize it. Therefore, although the two formulas have identical results, the computation speed is quite different;

If the Pre-calculation function is fully utilized, the code execution speed can be greatly improved. For example, the angle-to-radian operation is to multiply the angle by the circumference rate and then divide it by 180. Generally, j = k * Math. PI/180.0 is written in this way according to natural habits;

The preceding formula obviously does not use the pre-computing function of C #. If it is changed to the following formula:
J = k * (Math. PI/180.0 );
It will be found that the performance improvement is very obvious, about 70% faster;

3. reduce redundant computing

The code before optimization is as follows. This is a function for rotating points. Sin (Angle) and Cos (Angle) are calculated twice each time, so redundant computation exists.

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;
}

 

The optimized code is to eliminate redundant computing. The optimized code is as follows:

 

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;

}

 

The optimized code sin (angle) and cos (angle) are computed only once. It is "one calculation and two operations", and the performance is improved by about 30%.

 

If you want further optimization, you can remove the Temporary Variable pret and improve the overall performance by about 5%. The Code is as follows:

 

Private point rotatept (double angle, point pt)

{

Angle =-angle;

Double SIN_ANGLE = Math. Sin (angle );

Double COS_ANGLE = Math. Cos (angle );

Return new Point (int) (pt. X * COS_ANGLE-pt. Y * SIN_ANGLE ),

(Int) (pt. X * SIN_ANGLE + pt. Y * COS_ANGLE ));

}

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/qiqi5521/archive/2006/12/20/1450609.aspx

Humble Opinion

String ax = string. Empty;
Note: Do not use: string ax = ""; to determine whether ax is null:
The efficiency of ax. Length = 0 is higher than that of ax = string. Empty, but what I usually do is ax. IsNullorEmpty

For "variables" that do not need to be changed, remember to declare them with constants.

 

I try to replace the for loop with foreach. I remember where I saw it. The running time of foreach is 1/3 of that of. Also, try not to write judgment statements in the loop body, because it will affect the efficiency. After all, once you loop, the program will make a judgment so that there will be N cycles and N judgments, high efficiency.

Note
In the for loop, many people like for (int
I = 0; I <xxx. Length; I ++) {}, it is best to store xxx. Length in a variable and then bring it into the for loop, because every judgment will read
The xxx. Length value is a waste of time. Although the intelligent compiler will help you complete this, it is best to understand this. Do not declare variables or initialize them in a loop.

 

For the IDisposed interface, you should remember to release it when you use it. So, I usually use using (XXXXX xx = new XXXXX) {Your Code} When declaring it}

 

In vs2008, JavaScript-like var can be used, but var is a strong type. It has been compiled into the desired type before compilation, without affecting your speed.

 

For fields and attributes, the field access speed is faster than the attribute.

 

Linq is a good thing. In linq to object, it is very fast to solve the problem with linq, but it is annoying during debugging.

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.