## 18 July 2010

### Code Optimization Techniques for .net applications

Compiler optimization
• Technically It is the process of tuning the output of a compiler to minimize or maximize some attribute of an executable computer program.
• In simple terms it means improving the performance of your application.

Application is nothing but a program which is written to perform some specified task.

Why Optimization is required

But is optimization really necessary?ask yourself. Consider you are doing some important work and suddenly u get a busy cursor...like u are watching movie on youtube and an interesting part is there but suddenly buffering starts.

Some Tips for optimizing application
• Avoid unncessary variablesLook at the following example
```r=Radius of circle
p=piare
a=p*r*r;
```
is it right, no because u know value of 'p' will always be 3.14,So don't create variable for this type of conditions,Just say area=3.14*r*r;
• Avoid unnecessary cpu allocation
```read a
final_value=a*100*12*56;
write final_value
```
now all of us know 100*12*56 is equal to 67200 so why to put work for cpu, which we can do.just write final_value=a*67200;
• Avoid conditional loops inside Iteration loops like
```for(int x=1;x<7;x++)
{
//k and total are treated as random variables
if(k>99)
{
total+=x;
}
else
{
total-=x;
}
}
```
replace this with
```if(k>99)
{
for(int x=1;x<7;x++)
{
total+=x;
}
}
else
{
for(int x=1;x<7;x++)
{
total-=x;
}
}
```
• String Or String BuilderTake a right decision what to use string or StringBuilder.
• We want to store some string data which is going to be manipulated(like a new string will be appended or may be removed from the existing one) many times(considerable more than twice), in this situation StringBuilder will be better as string is immutable.
• But for small operations, means we want to store some string data which will be hardly one or two times manipulated string will be better choice.
• Comparing Non-Case-Sensitive StringsIn an application sometimes it is necessary to compare two string variables, ignoring the cases.
• Better1 : string.Compare(string1,string2)==0
• Use of collection classes instead of arrays,again use of generic collection classes.
• Use String.Empty when want to compare with blank stringex:-replace if(s=="") with if(s==string.Empty)
• Use structures instead of classes if type is going to be have less functionality.
• Avoid creating global variables.
• Avoid unnecessary try catch blocks(try to avoid exceptions by compile time logic).
• 11.Avoid Division Operations
(In the subsequent posts,we will back with some techniques.
Responses are always appreciated.Feel free to put your suggestion for optimations.)
:)

#### 1 comment:

1. So happy to see my first article :)

Your comments, Feedbacks and Suggestions are very much valuable to me :)