Wednesday, February 9, 2011

Tips on improving performance in Asp.Net

Improve Perfomance in ASP.net

1. Use Foreach loop instead of For loop for String Iteration.

2. Check “Page.IsPostBack”. To avoid repetition code execution.

3. GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

4. Turn off Session State, if not required.


5. Select the Release mode before making the final Build for your application.
This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

6. Disable ViewState when not required.
EnableViewState="false"

7.Use Caching to improve the performance of your application.

8. Use StringBuilder instead of String class.Strings occupy different memory location in every time of amended where stringbuilder use single memory location

9. Avoid Exceptions: Use If condition (if it is check proper condition)

10. Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

11. Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

12. Use Repeater control instead of DataGrid , DataList as it is efficient, customizable, and programmable.

13. Use single css file instead of multiple css file.

14. Don't make the member variables public or proteted. try to keep private and use public/protected as properties.

15. Use strString=string.Empty instead of strString=""

16. Use Server.Transfer instead of Response.Redirect.


More to come soon..........

Manually sorting gridview

private DataSet GetData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

GridView HTML Code:
The columns are generated automatically for the GridView control which are bound to the data source. Take a look at the HTML generated by the GridView control to have a clear picture.




public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}

private void SortGridView(string sortExpression,string direction)
{
//Cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}